1

興味深い質問を提示するコードがあります(私の意見では)。

/*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

4

5 に答える 5

7

これは、scanf を使用して "2.3" を読み取るときに、スキャンが停止しているが、"." を消費していないためです。「.3」で。したがって、次に scanf を呼び出すと、".3" の読み込みから開始されます。

詳しく言うと、scanf 呼び出しは 1 行のテキストに制限されません。scanf() は、タブ、スペース、改行を含む空白をスキップします。

于 2009-07-25T13:49:09.623 に答える
0

の行を読み取り、各行の解析にsscanfを使用します。私は他の人にも同意しますが、sscanfよりも優れた方法があります。

于 2009-07-25T14:24:28.983 に答える