gpt4 book ai didi

c - scanf 的问题,C. 浮点异常

转载 作者:太空宇宙 更新时间:2023-11-04 01:14:38 25 4
gpt4 key购买 nike

我正在学习 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 没关系),显然稍后停止。为什么?

谢谢。

最佳答案

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

关于c - scanf 的问题,C. 浮点异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4473475/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com