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>
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With