Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does pow() subtract 1 from my result? [duplicate]

Tags:

c

math

codeblocks

I'm new with C programming, and I've written this code as I've been asked to do something using mainly printf() and scanf(). I know there could be better ways to handle this, which I'll need to learn soon, but anyways, for now this is what I have:

int add1, add2, exponent, exponent_result, multiplier, parenthese, product, sub, total;

printf("Let's try a slightly more complex calculation, in which we'll use an exponent.\n\n");
printf("Type 5 whole numbers or integers.\n\n");
scanf("%i %i %i %i %i", &add1, &add2, &exponent, &multiplier, &sub);
printf("Out of the numbers you typed, we're going to make this operation: (%i + %i^%i) * %i - %i\n\n", add1, add2, exponent, multiplier, sub);

exponent_result = pow(add2, exponent);
parenthese = add1 + exponent_result;
product = parenthese * multiplier;
total = (add1 + exponent_result) * multiplier - sub;

printf("Per PEMDAS, the correct order of operation is Parentheses, then Exponents, then Multiplications and Divisions, and finally Additions and Subtractions.\n\n");
printf("Therefore: (%i + %i^%i) * %i - %i\n\n", add1, add2, exponent, multiplier, sub);
printf("...is equal to: (%i + %i) * %i - %i\n\n", add1, exponent_result, multiplier, sub);
printf("...is equal to: %i * %i - %i\n\n", parenthese, multiplier, sub);
printf("...is equal to: %i - %i\n\n", product, sub);
printf("...is equal to: %i", total);

If you run this code, you'll realize that the output for exponent_result, which is calculated using the pow() function, always has 1 subtracted from it. For instance, if exponent_result is supposed to be the result of 5^3, the result for that will be 124 instead of 125.

What am I doing wrong?

Fyi, I have this at the beginning of my file.

#include <stdio.h>
#include <math.h>
like image 354
Isaac Asante Avatar asked Aug 31 '17 09:08

Isaac Asante


1 Answers

pow is evaluated in floating point arithmetic, and is probably implemented as pow(x, y) = exp(y * log(x)).

This can cause the result to "go off": you probably get a value just shy of 125, which is truncated to 124 when the double return type from pow is converted back to an int.

The simplest remedy is to build your own pow function for integral arguments. See The most efficient way to implement an integer based power function pow(int, int)

like image 82
Bathsheba Avatar answered Nov 07 '22 03:11

Bathsheba