I'm trying to finish some basic coding exercise and I have already figured out how to fix it but I would just really like to understand what's going on.
#include <stdio.h>
#include <math.h>
int main(void) {
int first, second, third, fourth, fifth, sumOne, sumTwo, product;
printf("Enter integer 1: ");
scanf("%d", &first);
printf("Enter integer 2: ");
scanf("%d", &second);
printf("Enter integer 3: ");
scanf("%d", &third);
printf("Enter integer 4: ");
scanf("%d", &fourth);
printf("Enter integer 5: ");
scanf("%d", &fifth);
sumOne = first + second;
sumTwo = third + fourth;
printf("Result = %d", pow ((sumOne * sumTwo), fifth));
return 0;
}
I have been reading and I found out that pow provides a double result. I found that by changing the placeholder on the last printf() statement to %.0f, I get the desired result. Reason why I used %d is because I didn't want to get decimals in the output. I could also modify the data type and to double instead of int and just limit the decimals again on the final result.
I think my question is why have I been getting incorrect result with the use of %d as placeholder? Thank you.
%d
expects its corresponding argument to have typeint
;pow
returns adouble
. These types have different sizes and different representations - the binary representation of123.0
(double
) is completely different from the binary representation of123
(int
):Because of how
printf
is defined, it doesn't know the actual types of its arguments - it doesn't know that the argument corresponding to the result ofpow
is adouble
instead of anint
. Instead, it expects the first argument to be anint
because you used%d
, so it's not interpreting that value correctly.Crank up your warnings on your compiler.