【问题标题】:Problem with scanf, C. Floating point exceptionscanf 的问题,C. 浮点异常
【发布时间】:2010-12-17 18:07:21
【问题描述】:

我正在学习 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,它会打印“那里?” (所以 scanf 没关系)并稍后停止,显然。为什么?

谢谢。

【问题讨论】:

  • 因此,如果您键入 9999 以外的任何内容,它会崩溃而不打印“那里”? “崩溃”是什么意思?它有什么作用?段错误?你用调试器单步执行了吗?
  • @Falmarri:大概会产生浮点异常...
  • 没错,它会产生一个浮点异常。如果我输入 9999,它会在那里打印吗?并停下来。如果我输入其他内容,则会引发浮点异常

标签: c exception floating-point scanf


【解决方案1】:

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

【讨论】:

  • 我应该用什么来代替scanf? :) 即使 max 变为 0,我的 func rev 也永远不会被调用......所以它会改变一些东西吗?
  • @Ant:我没有说改变你对 scanf 的使用。我说这根本不是你的问题。您的 rev 功能不起作用。尝试使用我们建议的调试器来帮助您了解原因。如果您需要一些证据,请将您的主要内容更改为只需致电 rev(123) 看看会发生什么。
  • 好吧,也许明白了。抱歉..我 chenge rev 以便在'return 9' 并且程序可以工作,所以这绝对是一个 rev 问题......对不起;)
  • 我最初给出了完整的答案,但我和 Jefromi 在一起。你的 rev() 函数有一个错误,它不涉及 scanf()。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-16
    • 2010-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-04
    相关资源
    最近更新 更多