0

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

heres a screenshot

Daniele Santi
  • 3,084
  • 4
  • 30
  • 30
  • 1
    Hello and welcome to Ask Ubuntu! Images and screenshots can be a nice addition to a post, but please make sure the post is still clear and useful without them. Don't post images of code or error messages. Instead copy and paste or type the actual code/message into the post directly. – Daniele Santi Jan 23 '19 at 10:46
  • 4
    Possible duplicate of [How to compile a C program that uses math.h?](https://askubuntu.com/questions/332884/how-to-compile-a-c-program-that-uses-math-h) – Sergiy Kolodyazhnyy Jan 23 '19 at 10:57
  • 1
    @karel Already voted. I agree, it's sufficiently relevant to Ubuntu and common enough issue to be open. – Sergiy Kolodyazhnyy Jan 23 '19 at 11:29
  • I don't think this is anything to do with library linkage - it's a basic programming error: trying to use the return value of `pow` (which has type double) as an argument to the integer modulo operator `%` – steeldriver Jan 23 '19 at 12:07
  • ... in addition, `cmath` isn't `math.h` and AFAIK `g++` (unlike `gcc`) links `libm` by default – steeldriver Jan 23 '19 at 13:16

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
  • 131,985
  • 21
  • 239
  • 326