0

I starting programming with language C and I have problem with using pow function.

I wrote this code

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main()
{
    double result = 3 / 2 + 12 - (pow(5, 3) - 2)/6;
    double result2 = 3 / 2 + 12 - (5*5*5 - 2)/6;
    printf("%g %g", result, result2);
    return 0;
}

result has value -7.5, result 2 has value -7. I dont have any idea why its not equal.

  • 5
    `result2` is evaluated as `int`. `result` is as `double`, because `pow` returns `double` – Eugene Sh. Mar 25 '21 at 21:42
  • 1
    Try `double result2 = 3 / 2 + 12 - ((double)5*5*5 - 2)/6;` – David C. Rankin Mar 25 '21 at 21:43
  • but result 2 is correct @DavidC.Rankin – stilldreamer Mar 25 '21 at 21:47
  • but result 2 is correct @EugeneSh. – stilldreamer Mar 25 '21 at 21:49
  • Because 3/2 is evaluated as integer as well and compensating that one half difference – Eugene Sh. Mar 25 '21 at 21:51
  • `(pow(5, 3) - 2)/6` --> `(125.0 - 2)/6` --> `123.0/6` --> `20.5` – dbush Mar 25 '21 at 21:53
  • 2
    You are running into multiple integer division problems. `result` is `(3/2) == 1 + 12 - 20.5 = -7.5`. `result2` is `3/2) == 1 + 12 - 20 = 7` (right only by *Happy Accident*) To make `result` properly correct, `result = 3./2 + 12 - (pow(5, 3) - 2)/6;` (which is `-7` -- **note:** the `'.'` after `3`) – David C. Rankin Mar 25 '21 at 21:54
  • double result = (double)3 / 2 + 12 - (pow(5, 3) - 2)/(double)6; is this correct version? – stilldreamer Mar 25 '21 at 21:56
  • Short answer - YES. Using `3.` (or `3.0`) also ensures the constant `3` is of type `double`. But also note there are times when the mixing of integer math with floating-point math is **intentional**. So the "correct version" is the computation using the math your intended. – David C. Rankin Mar 25 '21 at 21:56
  • Thank you for your help. I am not sure if i corectly understand your second and third sentences. Should i preffer "(double)" or "3." ? – stilldreamer Mar 25 '21 at 22:06
  • In C, any numeric constant defaults to type `int`. So `3` is type `int` unless you change the default. Adding `3.` or `3.0` changes the type to `double` as does an explicit cast `(double)3`. So `3.` and `(double)3` are entirely equivalent. – David C. Rankin Mar 25 '21 at 22:08
  • See [C11 Standard - 6.4.4.1 Integer constants](http://port70.net/~nsz/c/c11/n1570.html#6.4.4.1) and [6.4.4.2 Floating constants](http://port70.net/~nsz/c/c11/n1570.html#6.4.4.2) (remember the C standard is written to guide compiler writers as much as it is written for programmers, do don't let the sometimes awkward wording bother you -- you will get used to it) – David C. Rankin Mar 25 '21 at 22:12
  • Ok, i understand. Thank you. Have a good time. – stilldreamer Mar 25 '21 at 22:29

0 Answers0