興味深い質問を提示するコードがあります(私の意見では)。
/*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;
}
入力する数値の順序は、浮動小数点数、次に 10 進数 (基数、次に指数) であることに気付いた場合。しかし、整数基数と浮動小数点指数で入力を入力すると、奇妙な結果が生成されます。
[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.
浮動小数点指数の 2 番目の数値を次の入力に戻すようです。舞台裏で何が起こっているのか誰かが説明できることを望んでいました。これは配列の境界をチェックしない scanf() の作業であることは知っていますが、誰かが私にもう少し深い理解を与えることができれば、本当に感謝しています。ありがとうスタックオーバーフロー。-MI
編集。皆さんの意見に感謝したいと思います。他の回答は大歓迎です。ありがとう、SO