gpt4 book ai didi

c - 为什么当用户输入 -0.1 时这个循环没有立即中断

转载 作者:太空狗 更新时间:2023-10-29 15:54:08 26 4
gpt4 key购买 nike

当我偶然发现这段代码时,我正在复习我为算法课做的一些练习,但它并没有像我想象的那样工作。

所以练习如下:编写一个程序,要求输入一个正整数,然后打印它的 double 值,除非该数字为负数。

代码如下:

int main(void) {
int n = 1;

while (n >= 0) {
printf("Veuillez introduire un nombre entier positif: ");

if (!(scanf("%i", &n)) || n < 0)
break;

printf("Le double de %i est de: %i\n", n, (2 * n));
}
}

很简单。

问题是,如果我尝试输入一个字符,一个负数,程序会立即停止……正如预期的那样,但如果我输入“-0.1”,它首先打印 0 的两倍,即 0,然后再次向上运行循环到 if 语句。

如果我只输入 0 甚至 -0,它不会继续运行(它应该这样做,因为 0 不是负数)。

这是输出:

Veuillez introduire un nombre entier positif: -0  
Le double de 0 est de: 0
Veuillez introduire un nombre entier positif: 1
Le double de 1 est de: 2
Veuillez introduire un nombre entier positif: -0.1
Le double de 0 est de: 0
Veuillez introduire un nombre entier positif:

到此为止。

我实在想不通。对不起,如果这是微不足道的。

感谢您的宝贵时间。

注意:这是我的第一篇文章,我还没有在这里找到答案,所以如果您找到它或有任何反馈,请随时发布,我们将不胜感激。

编辑:用文本交换输出截图

最佳答案

使用格式%iscanf() 读取一个整数。如果键入 -0.1,则整数为 -0。这不小于 0,因此循环继续。

下一次循环,它会尝试从 .1 中读取一个整数。由于这不是整数,因此扫描失败并且 scanf() 返回 0。这导致 !scanf("%i", &n) 为真,因此执行 break; 并停止循环。

关于c - 为什么当用户输入 -0.1 时这个循环没有立即中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48716325/

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