scanf()导致奇怪的结果

mik*_*key 1 c c++ 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;
}
Run Code Online (Sandbox Code Playgroud)

如果您注意到要输入的数字的顺序是浮点数,然后是十进制数(基数,然后是指数).但是当我输入带有整数基数和浮点指数的输入时,它会产生一个奇怪的结果.

[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.
Run Code Online (Sandbox Code Playgroud)

它似乎将浮点指数的第二个数字推回到下一个输入.我希望有人可以解释幕后发生的事情.我知道这是scanf()的工作,不检查它的数组边界,但如果有人可以给我一些更深刻的理解,我真的很感激它.谢谢Stack Overflow.-MI

编辑.只是想感谢大家的意见.任何其他答案都更受欢迎.再次感谢,SO

Eri*_*ric 7

这是因为当您使用scanf读取"2.3"时,扫描停止,但不消耗"." 在".3".因此,当您对scanf进行下一次调用时,它首先读入".3".

详细说明,scanf调用不限于一行文本.scanf()跳过空格,包括制表符,空格和换行符.


pax*_*blo 5

其他人已回答您的具体问题,但我想提供一条建议.永远不要使用scanf()fscanf().永远.认真.

[f]scanf()操作失败总是将文件指针留在不确定的位置.因为从用户的大多数输入通常是基于行(除了在图形用户界面),使用的选项fgets(),并sscanf()始终是更好,在我看来.

它的优点是可以将输入指针留在已知点(下一行的开头),允许您以多种不同的方式操作刚读入的行,而不仅仅是由scanf()系列决定的.

换句话说,如果sscanf()失败,你仍然有可用于其他目的的线路(重新扫描不同的格式字符串,甚至只是输出错误),而不必通过stdio体操回到线路的开头文件(文件很难,终端的标准输入不可能).