3

While trying to solve credit, I get the following error

screenshot of the error message

rem and number1 are declared as long and even if I change them to int, I still get the same error.

Please provide a solution and explain what the mistake is!

8

The remainder operator (otherwise known as the modulo operator) % is a binary operator (i.e., takes exactly 2 operands) and operates only on integer types (e.g., short, int, long, long long, etc).

It appears from the error message that the variable number1 is of type double. Also, the function pow from the math library returns a value of type double. These two values are the main cause for the error.

There are many solutions to this each of which depend on what you want to do. I'll demonstrate a couple of them:

  1. Casting the operands to ints

    foo = (int) bar % (int) quux; // WARNING: you'll be risking to lose data
    
  2. Declaring number1 to be of an int type and writing your own version of pow that maybe takes and returns ints

    // works only for non-negative integer exponents
    int myPow(int n, int exp)
    {
        int result = 1;
        for (; exp > 0; exp--)
            result *= n;
    
        return result;
    }
    
    // some code
    
    foo = number1 % pow(bar, quux);
    
  3. Declaring number1 to be of an int type and using a library function like round, to round the value returned from pow then casting it to an int

    foo = number1 % (int) round(pow(bar, quux));
    
| improve this answer | |
  • I'm using long integer type. I have also tried the same with int, but getting the same error.. – Prateek Pande Jan 15 '15 at 15:16
  • @PrateekPande please read the answer carefully! "Also, the function pow from the math library returns a value of type double" – Kareem Jan 15 '15 at 15:45
  • Thank you for this! – iamcarlos Aug 18 '18 at 15:46

You must log in to answer this question.

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