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!
CS50 Stack Exchange is a question and answer site for students of Harvard University's CS50. It only takes a minute to sign up.
Sign up to join this communityThe 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 int
s
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 int
s
// 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));