简体   繁体   中英

Problem with scanf, C. Floating point exception

i'm learning C.

i'm using ubuntu and have Code::Blocks as IDE i have this code:

#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. if i type 9999, it prints 'there?' (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. Try running it in a debugger, and you'll see that your algorithm is bad: eventually max becomes zero and you divide by it. I'll leave fixing that as an exercise for the reader; the problem isn't anything to do with scanf.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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