Q
Q
Qubc2020-07-31 18:35:17
C++ / C#
Qubc, 2020-07-31 18:35:17

Why is (int) pow ( variable1, variable2 ) cast different from (int) pow ( constant1, constant2 )?

#include <stdio.h>
#include <math.h>
int main() {
  int base = 10;
  int k = 2;
  printf("%d\n", (int) pow(base, k) );//99
  printf("%d\n", (int) pow(base, 2) );//99
  printf("%d\n", (int) pow(10, k) );//99
  printf("%d\n", (int) pow(10, 2) );//100
  return 0;
}

gcc (MinGW.org GCC-6.3.0-1) 6.3.0

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
res2001, 2020-07-31
@res2001

In the latter case, apparently, some kind of compiler optimization played and there was no real call to pow.
In general, 99 is obtained as a result of converting a floating point to an int.

A
AnT, 2020-07-31
@TheCalligrapher

Your code is basically incorrect. The function powis not declared. The C language does not allow calls to undeclared functions. Even if your compiler manages to compile it somehow, the behavior is still undefined.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question