0

I compiled a code on UBUNTU app using cmath library for raising powers, but it shows an error.

heres a screenshot

1 Answers1

1

The error is because you are trying to use the (integer) modulo operator % with the return value of pow (which has type double).

Ex. given

$ cat pow.cpp
#include <iostream>
#include <cmath>

int main(void)
{
  int i = 2;
  int num = 345;

  num = num % pow(10,i);

  std::cout << "num: " << num << std::endl;
}

then

$ g++ -o pow pow.cpp
pow.cpp: In function ‘int main()’:
pow.cpp:9:13: error: invalid operands of types ‘int’ and ‘double’ to binary ‘operator%’
   num = num % pow(10,i);
         ~~~~^~~~~~~~~~~

If you explicitly cast the return value to int

  num = num % (int)pow(10,i);

it will "work" - but you will need to satisfy yourself that it is giving you the intended result:

$ g++ -o pow pow.cpp
$ ./pow
num: 45

[Note that you don't need to explicitly link libm when using g++ since - unlike gcc - it is linked by default (i.e. unless you add the -nostdlib flag)]

steeldriver
  • 142,475