Unable to use modulo with pow() in C

Viewed 542

I'm writing a program and have been stuck in this part for quite some time.

int y;
y = 111 % pow(10,2);
printf("%d",y);

The error shown is invalid operands of types 'int' and 'double' to binary 'operator%'.

Is there any workaround to this (i.e. using the pow() function)?

2 Answers

In C, pow returns a double irrespective of the types of the input parameters.

And a double cannot be used as an argument to %.

Hence the compiler issues an error.

The solution is to use 10 * 10 rather than using pow to raise a number to its second power. Note that because % has the same precedence as * you'd need to write the expression as 111 % (10 * 10).

pow actually returns a double, on which the modulus operator % cannot operate.

Try using the fmod method (declared in math.h) instead.

Related