I have a problem with a modulo in “Credit”. That is a part of my initial code:
#include <stdio.h>
#include <cs50.h>
#include <math.h>
int main(void)
{
//Determine a variable for a card number
long long number;
//Determine a variable for all odd-position digits
int odd;
//Prompt user for a card number that has to be > 0; prompt again if < 0
do
{
number = get_long_long ("Number: ");
}
while (number <= 0);
//Determine if the number is valid
for (int i = 1; i <= 16; i = i + 2)
{
//Extract all odd-position digits
odd = (number % (pow (10, i) - number % (pow (10, i-1)) ) / pow (10, i-1);
}
}
I received the following error:
credit.c:45:22: error: invalid operands to binary expression ('double' and 'double')
odd = (number % (pow (10, i)) - number % (pow (10, i-1)) / pow (10, 15);
I managed this problem by determining a new variable “long long pow_odd” and multiplying instead of powering. Now my code looks like this:
#include <stdio.h>
#include <cs50.h>
#include <math.h>
int main(void)
{
//Determine a variable for a card number
long long number;
//Determine a variable for all odd-position digits
int odd;
//Determine variables for a powering of 10, power is an odd number
long long pow_odd;
//Prompt user for a card number that has to be > 0; prompt again if < 0
do
{
number = get_long_long ("Number: ");
}
while (number <= 0);
//Determine if the number is valid
for (int i = 1; i <= 16; i = i + 2)
{
//Power 10 into i
for (pow_odd = 10; pow_odd < pow (10, i); pow_odd = pow_odd * 100)
{
}
//Extract all odd-position digits
odd = (number % pow_odd - number % (pow_odd / 10)) / (pow_odd / 10);
}
}
Although the code works properly now, it looks even less fancy than it was at the beginning :)
May be you know what is the reason for the error “invalid operands to binary expression ('double' and 'double')” in my initial code and is it possible to cope with it without a new variable?
Thank you!