我有一段代碼提出了一個有趣的問題(在我看來)。scanf()導致奇怪的結果
/*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;
}
如果你會發現號的順序輸入的是浮點數,然後十進制數(基本號碼,然後指數)。但是當我用整數基和浮點指數輸入輸入時,它會產生一個奇怪的結果。
[[email protected] ~/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()沒有檢查它的數組邊界的工作,但如果有人能給我更深的理解,我會非常感激。 感謝堆棧溢出。 -M.I.
編輯。 只是想感謝大家的意見。任何其他答案都更受歡迎。 再次感謝,S.O.
好的,我明白了,謝謝。 – mikeyickey 2009-07-27 14:00:14