简体   繁体   English

scanf问题,C。浮点异常

[英]Problem with scanf, C. Floating point exception

i'm learning C. 我正在学习C。

i'm using ubuntu and have Code::Blocks as IDE i have this code: 我正在使用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;
}

I'm doing it in this way cause my book isn't clear...however, the problem is that it raise a Floating Point exception, in scanf...i'm typing normal numbers... the strange thing is that if i type everything but 9999, the program crash. 我这样做是因为我的书不清楚...但是,问题是它引发了一个浮点异常,在scanf中...我正在输入正常数字...奇怪的是如果我键入除9999以外的所有内容,程序将崩溃。 if i type 9999, it prints 'there?' 如果我输入9999,它会显示“有?” (so scanf it's ok) and stop later, obviously. (这样就可以了),然后稍后再停止,显然。 why? 为什么?

Thank you. 谢谢。

The two existing (be sure to return the result in rev , and put \\n on the ends of printfs to be sure they make it through the buffer) answers are good points, but not the thing that's actually triggering your floating point exception. 已有的两个答案(请确保将结果返回rev ,并将\\n放在printfs的末尾以确保它们通过缓冲区)是正确的答案,但实际上不是触发浮点异常的东西。 Try running it in a debugger, and you'll see that your algorithm is bad: eventually max becomes zero and you divide by it. 尝试在调试器中运行它,您会发现算法不好:最终max变为零,然后除以它。 I'll leave fixing that as an exercise for the reader; 我将把它修正为读者的练习。 the problem isn't anything to do with scanf. 问题与scanf无关。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM