为两个几乎相同的代码显示不同的输出

编程入门 行业动态 更新时间:2024-10-23 07:36:24
本文介绍了为两个几乎相同的代码显示不同的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在以下两个代码中,我无法理解问题所在.第一个代码是:

In the following two codes I cannot understand the problem. First code is:

#include <stdio.h> main() { int num1, num2; scanf("%d%d", &num1, &num2); printf("I LOVE MY INDIA\n"); //here is '\n' after the statement printf("%d", num1/num2); return 0; }

这里如果输入是 num1=2 和 num2=0 那么在 gcc 编译器中输出是:

Here if the inputs are num1=2 and num2=0 then in gcc compiler the output is:

我爱我的印度浮点异常(核心转储)

I LOVE MY INDIA Floating point exception (core dumped)

但是对于第二个代码:

#include <stdio.h> main() { int num1, num2; scanf("%d%d", &num1, &num2); printf("I LOVE MY INDIA"); //here is no '\n' printf("%d", num1/num2); return 0; }

对于与之前显示相同的输入:

For same input as before this is showing:

浮点异常(核心转储)

这两个代码之间只有一个区别.在第一个代码中,在 I LOVE MY INDIA 之后有一个 \n,而在第二个代码中没有 \n.请解释为什么 I LOVE MY INDIA 没有显示在第二个代码中.

In between these two codes there is only one difference. In the 1st one there is a \n after I LOVE MY INDIA and in the 2nd code there is no \n. Please explain why I LOVE MY INDIA is not being displayed in the 2nd code.

推荐答案

默认情况下,标准输出 (stdout) 是行缓冲的.

By default, the standard output (stdout) is line buffered.

在第一种情况下,printf() 中的换行符 \n 导致输出缓冲区在崩溃之前被刷新到输出发生.所以,你必须看到打印语句.

In first case, the newline \n in the printf() causes the output buffer to be flushed to the output before the crash happens. So, you got to see the print statement.

OTOH,在第二种情况下,缺少\n会导致缓冲区保存数据,而下一条语句会导致异常和程序异常终止.因此,缓冲的数据没有机会刷新到输出终端.因此,您没有视觉输出.

OTOH, in the second case, lack of the \n causes the buffer to hold the data, and the next statement causes the exception and an abnormal termination of the program. So, the buffered data did not get a chance to be flushed to the output terminal. Hence, you got no visual output.

也就是说,除以零会导致未定义行为,严格来说,您的程序不能依赖于产生任何预期的输出.

That said, a division by zero causes undefined behavior and strictly speaking, your program cannot be relied upon to produce any expected output.

更多推荐

为两个几乎相同的代码显示不同的输出

本文发布于:2023-11-10 02:18:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574072.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:两个   代码

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!