为什么我没有得到预期的输出? [英] why i am not getting the expected output?

查看:51
本文介绍了为什么我没有得到预期的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int main()
{
  int x;
  float y;
  char c;

  x = -4443;
  y = 24.25;
  c = 'M';

  printf("\nThe value of integer variable x is %f", (float)x);
  printf("\nThe value of float variable y is %d", y);
  printf("\nThe value of character variable c is %f\n",c);
    return 0;
}

输出:

The value of integer variable x is -4443.000000
The value of float variable y is 0
The value of character variable c is 24.250000

为什么我没有得到预期的输出?

Why am I not getting the expected output?

但是当我使用外部转换时,我得到了预期的输出:

But when I am using external casting I am getting expected output which is:

The value of integer variable x is -4443.000000
The value of float variable y is 24
The value of character variable c is 77.000000

推荐答案

为什么我没有得到预期的输出?

why i am not getting the expected output ?

简答:因为你的期望是错误的.

Short answer: Because your expectations are wrong.

您正在指示编译器从 y 所在的位置读取一个整数.这是错误的.格式说明符不告诉编译器进行强制转换,只告诉编译器需要什么类型,并且相信会提供正确的类型.

You're instructing the compiler to read an integer from where y is. Which is wrong. Format specifier don't tell the compiler to do casts, just what type to expect, and trust you to provide the right type.

该行为可能是由于例如float 存储在 8 个字节中.在这种情况下,高位字节将为 0.但是 int 存储在 4 个字节中.所以你告诉编译器从 y 的位置读取 int,它读取前 4 个字节,它们是 0,并打印 0...

The behaviour can be due to the fact that, for example, a float is stored in 8 bytes. The high-order bytes will be 0 in this case. But an int is stored in 4 bytes. So you tell the compiler read the int from where y is, it reads the first 4 bytes, which are 0, and prints 0...

正如约翰在评论中指出的,这是 UB,这意味着任何事情都可能发生:

As John pointed out in the comments, this is UB, which means that anything can happen:

7.21.6.1/9

如果转换规范无效,则行为未定义.282) 如果任何参数不是相应转换规范的正确类型,则行为未定义.

If a conversion specification is invalid, the behavior is undefined.282) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

这篇关于为什么我没有得到预期的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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