0

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!

1

the definition of the pow function says that it returns a double that is the reason of your error, since the operator modulo requires integers, it is possible that it works if we do a casting although I am not sure:

odd = number % (int) round((pow (10, i))- number % (int) round((pow (10, i-1))) / (int)round(pow (10, i-1));
1
  • I've done the casting using a long long instead of an integer for numbers like 10^16 and now it works! Thank you so much! Now the part of the code looks like this: odd = (number % (long long) round (pow (10, i)) - number % (long long) round (pow (10, i-1)) ) / (long long) round (pow (10, i-1));
    – Olga
    Feb 24 '18 at 8:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .