我有一段代码呈现一个有趣的问题(在我的意见)。

/*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函数的()不检查其数组边界的工作,但如果有一个人可以给我一些更深入的了解我会很感激。 由于堆栈溢出。 -M.I。

编辑。 只是想感谢大家的投入。任何其他的答案是更然后欢迎。 再次谢谢,S.O。

有帮助吗?

解决方案

当读取第一“2.3”的scanf读上升到“”。意识到这不再是一个有效的整数和停止。所以。“3" 是留在缓冲区中,然后你输入‘2 3.4’这样。” 3 \ N2 3.4" 是在缓冲区中。当scanf函数解析它获得。” 3" 和‘2’就像你的例子显示了。

其他提示

这是因为当你使用scanf函数改为“2.3”,在扫描停在,但不消耗“”在。” 3" 。因此,当您对scanf函数的下一次调用,它开始通过读取。” 3" 。

要详细阐述,scanf的呼叫不限于一个文本行。 scanf()的跳过空白,包括制表符,空格和换行。

其他已经回答您的具体问题,但我想提供一个忠告。 从不使用scanf()fscanf()。永远。严重。

一个[f]scanf()操作时失败总是离开你的文件指针在一个不确定的位置。由于来自用户的大多数输入一般是基于线路(除了在图形用户界面),采用fgets()sscanf()的选择总是更好,在我的意见。

它离开输入指针在已知点(下一行的开始)的和优势的让你操作你刚才读在许多不同的方式行,而不仅仅是该决定由scanf()家族

在换句话说,如果sscanf()失败,你仍然有可用于其他用途的线(用不同的格式字符串重新扫描,甚至简单地输出一个错误的话),而不必经过stdio体操,回到开始该文件中的行(硬与文件,不可能用标准输入从终端)的

在C,scanf()的是用于从人类用户的现实世界输入基本无用 - 它是用于从数据文件中读取的固定格式文本。如果您正在使用C ++,你应该使用iostream的输入,并在这两种情况下,你确实应该写自己的分析例程用于特定输入要求。

我将读取该行,并使用sscanf的用于解析每一行。我同意其他人,还有比sscanf的更好的方法,虽然。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top