我有一段代码提出了一个有趣的问题(在我看来)。
/*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;
}
如果您注意到要输入的数字的顺序是浮点数,然后是十进制数(基数,然后是指数)。但是当我使用整数基数和浮点指数输入输入时,它会产生一个奇怪的结果。
[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.
它似乎将浮点指数的第二个数字推回下一个输入。我希望有人能解释幕后发生的事情。我知道这是 scanf() 不检查其数组边界的工作,但如果有人能给我更深入的理解,我将不胜感激。感谢堆栈溢出。-MI
编辑。只是想感谢大家的意见。任何其他答案都更受欢迎。再次感谢,所以