I understand how to use pow()
correctly I'm just wondering why when I run this code ans
= inf.
I am having a hard time understanding this.
Does this have anything to do with chars only being able to take on the values -128 to +127 and the way pow()
is calculated?
Does this have anything to do with the space in " %c"
as in my first scanf
param?
Linux 4.9.0-7-amd64 debian 4.9.110-1 gcc version 6.3.020170516
#include <stdio.h>
#include <math.h>
int main ()
{
char base, exp;
float ans;
printf("Enter base number : ");
scanf(" %c", &base);
printf("Enter exp number : ");
scanf(" %c", &exp);
ans = pow(base,exp);
printf("%c raised to the %c power equals %f", base, exp, ans);
return 0;
}
When you enter base
and exp
using %c
you get the characters '0'
- '9'
, not the integer values. So if you enter 0 and 0, the values you get (assuming ASCII encoding) will actually by 48, since that is the ASCII code for '0'
. The result of 4848 is roughly 5 x 1080.
You then save the resulting value in a float
. Assuming a float
is IEEE754 single precision, it can hold an exponent no larger that +/- 38. So you're attempting convert an out-of-range value which invokes undefined behavior, meaning the result is unpredictable. If you changed the type of ans
to double
you would see the actual result.