scanf问题,C。浮点异常

时间:2010-12-17 18:07:22

标签: c exception floating-point scanf

我正在学习C.

我正在使用ubuntu并将Code :: Blocks作为IDE 我有这个代码:

#include <stdio.h>

int rev (int num);

int main (){
    int numb = 0;

    printf("%d\n\n", numb);

    printf("Please enter a number. Enter 9999 to stop\n");
    scanf("%d", &numb);
    printf("there?");
    printf("%d\n", numb);

    while (numb != 9999){
        printf("The reversed number is %d\n", rev(numb));
        printf("Please enter a number. Enter 9999 to stop\n");
        scanf("%d", &numb);
    } /* end of while */

}

int rev (int num){
    printf("here?");
    int total = 0;
    long max = 10;
    long max_const = 10;

    printf("here");

    for (max; max < num; max *= 10);

    printf("%ld", max);

    max_const = max;

    for (int i = 0; i <= max_const; i *= 10, max /= 10){
        total += num / max * i;
    } /* end for */

    return total;
}

我这样做是因为我的书不清楚...但是,问题是它引发了一个浮点异常,在scanf中......我正在键入正常的数字......奇怪的是事情是,如果我输入除9999之外的所有内容,程序会崩溃。如果我输入9999,它打印'那里?' (所以扫描它没关系)并且显然是稍后停止。为什么呢?

谢谢。

2 个答案:

答案 0 :(得分:4)

现有两个(确保在rev中返回结果,并将\n放在printfs的末尾以确保它们通过缓冲区)答案是好点,但不是实际上触发浮点异常的事情。尝试在调试器中运行它,你会发现你的算法很糟糕:最终max变为零,你除以它。我会把这作为读者的练习;问题与scanf无关。

答案 1 :(得分:1)

您的rev功能需要返回反转的数字。