I have a piece of code that presents an interesting question (in my opinion).
/*power.c raises numbers to integer powers*/
#include <stdio.h>
double power(double n, int p);
int main(void)
{
double x, xpow; /*x is the orginal number and xpow is the result*/
int exp;/*exp is the exponent that x is being raised to */
printf("Enter a number and the positive integer power to which\n the first number will be raised.\n enter q to quit\n");
while(scanf("%lf %d", &x, &exp) ==2)
{
xpow = power(x, exp);
printf("%.3g to the power %d is %.5g\n", x, exp, xpow);
printf("enter the next pair of numbers or q to quit.\n");
}
printf("Hope you enjoyed your power trip -- bye!\n");
return 0;
}
double power(double n, int p)
{
double pow = 1;
int i;
for(i = 1; i <= p; i++)
{
pow *= n;
}
return pow;
}
If you'll notice the order of numbers to be entered is the floating point number and then the decimal number (base number and then the exponent). But when I enter the input with an integer base and floating point exponent it produces a strange result.
[mike@mike ~/code/powerCode]$ ./power
Enter a number and the positive integer power to which
the first number will be raised.
enter q to quit
1 2.3
1 to the power 2 is 1
enter the next pair of numbers or q to quit.
2 3.4
0.3 to the power 2 is 0.09
enter the next pair of numbers or q to quit.
It seems to push the second number of the floating point exponent back onto the next input. I was hoping some one could explain what was going on behind the scenes. I know that this is the work of scanf() not checking its array boundaries but if some one could give me some deeper understanding I'd really appreciate it. Thanks Stack Overflow. -M.I.
Edit. Just wanted to thank everyone for their input. Any other answers are more then welcome. Thanks again, S.O.