While trying to solve credit, I get the following error
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!
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
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:
Casting the operands to ints
foo = (int) bar % (int) quux; // WARNING: you’ll be risking to lose data
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);
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));