为两个几乎相同的代码显示不同的输出 [英] Showing different output for two almost same code

查看:52
本文介绍了为两个几乎相同的代码显示不同的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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=2num2=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.

这篇关于为两个几乎相同的代码显示不同的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆