移动的printf不同的线条给人不同的输出? (C) [英] Moving printf to different lines gives different outputs? (C)

查看:178
本文介绍了移动的printf不同的线条给人不同的输出? (C)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C,当我提出这个printf的行:的printf(%F \\ N,5/2); 到不同的线路输出变化。任何想法?

In C, when I move this printf line: printf("%f\n", 5 / 2); to different lines its output changes. Any ideas?

继承人的code:

#include <stdlib.h>
#include <stdio.h>


int main()
{   

    int a = 65;
    char c = (char)a;
    int m = 3.0/2;

    printf("%c\n", c);              
    printf("%f\n", (float)a);       
    printf("%f\n", 5.0 / 2);        
    printf("%f\n", 5 / 2.0);        
    printf("%f\n", (float)5 / 2);   
    printf("%f\n", 5 / (float)2); 
    printf("%f\n", (float)(5 / 2)); 
    printf("%f\n", 5.0 / 2);        
    printf("%d\n", m);              
    printf("%f\n", 5 / 2);


    system("PAUSE");
    return(0);
}

和继承人的输出:

A
65.000000
2.500000
2.500000
2.500000
2.500000
2.000000
2.500000
1
2.500000

如果我移动的printf(%F \\ N,5/2); 来第一线之一(一个输出和一间该输出65.000000)将打印0.000000(这是有道理的),而不是其现在2.500000。
任何想法?

And if I move printf("%f\n", 5 / 2); to one of the first lines (between the one that outputs A and the one that outputs 65.000000) it will print 0.000000 (which makes sense) instead of its now 2.500000. Any ideas?

推荐答案

您code为调用未定义的行为。

Your code is invoking undefined behavior.

您有义务用于打印的东西正确的数据在说明符的printf ,并没有这样做,是调用UB。因此,它是不重要的,并不奇怪,你获得在不同的位置不同的结果。

You are obligated to use the correct data specifiers for printing things in printf, and failing to do so is invoking UB. Thus it is unimportant and not surprising that you get different results at different places.

HTTP://en.cp$p$pference.com/ W / C / IO / fprintf中

如果一个转换说明是无效的,其行为是不确定的。

If a conversion specification is invalid, the behavior is undefined.

同样的不仅仅是C也是如此。

The same holds true for just c.

当调用未定义的行为,结果被定义随机而不是predictable,所以要求我们predict他们没有什么意义。

When invoking undefined behavior, the results are by definition random and not predictable, so asking us to predict them makes little sense.

这篇关于移动的printf不同的线条给人不同的输出? (C)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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