为什么一个整数和一个浮点数之和是一个整数? [英] Why is the sum of an int and a float an int?

查看:69
本文介绍了为什么一个整数和一个浮点数之和是一个整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

float d  = 3.14f;
int   i  = 1;
auto sum = d + i;

根据 cppreference.com i 添加到 d 时应转换为 float .但是,当我实际运行代码时,我发现 sum 是4.为什么会发生这种情况?

According to cppreference.com, i should be converted to float when it is added to d. However, when I actually run the code, I find that sum is 4. Why does this happen?

有趣的是,当我明确地将编译器置于C11模式时,我发现 sum 为4.14.C11标准更改会影响结果的哪些规则?

Interestingly, when I explicitly put my compiler into C11 mode, I found that sum was 4.14. What rules does the C11 standard change that affect the outcome?

如果我使用C ++编译器编译相同的代码会发生什么?

What would happen if I compiled the same code using a C++ compiler?

推荐答案

在C(和C ++)中,由于 3.14f +1 float 类型>将类型为 int 的类型升级转换为 float .

In C (and C++), 3.14f + 1 is a float type due to type promotion of int to float.

但是在C中,直到C90(包括C90),并且这样的标准很可能是您的C编译器默认值,它分配给 int 类型,产生4,因为 int 是具有自动存储期限的变量的默认类型.从C99开始,编译将由于隐式int被撤消而失败,尽管编译器可能仍会警告并带有警告.

But in C, up to and including C90, and such a standard may well possibly be your C compiler default, this is assigned to an int type, yielding 4, since int is the default type for a variable with automatic storage duration. From C99 onwards, compilation will fail as implicit int was withdrawn, although compilers might still permit it, with a warning.

(在C ++ 11及更高版本中, auto 指示编译器推断类型. sum 将是值为 3.14f + 1 .仍可以使用C ++ 98或C ++ 03进行编译,但会生成有关C ++ 11扩展的警告.组织/#Z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAKxAEZSBnVAV2OUxAHIB6bgajQBbAA54ANpmJ9UwgnlQA7BiACkABgCCvPgFoAHsj5EBqEeMx8Ahgz4BhAHQCEqVAwuL3AMz591W/j66DAToKgDMACLIAJxqPjrBoZEx0fGJ4VG0tH7apoR8%2BcZCohJWNrYqAEwAQlXV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ZWE4fhhHEaRjlUfsrl0ZgDFMZACmsaQ7GVn1PGK1BKtwWrIkoWhknS3JClKSpakaXWmM6csekGXgRkmTtcba5Zuu2QbDkQBRxs0WbFteRA1u%2Bfb3GBU7IWyPIShcNF0y9Lm1QTPFOhJSlaUZYwWXsMFCPPS2RNcP9gPlQuYO1XEDX4EQUjvfQdgdTdLWVO8kMZn1NZ1gj42TWEtUG2o0RbypAyJomoeE5mO2MHtpC9vP5OwCdtznQKFBXZP9OVKQ90j63H7t9tnDvZUX0/X9JUyrAz7tVAec9KzLyRlNXC9hEyVBWmEL4KwvhqFwtNTaHcj6dhPqTee1Zaz1g/I3TB7Zj7nwgR%2BSoBVXpkN6nGR8xAtRpmWEAA"的rel = noreferrer">这是铛做什么,例如.在C ++ 11中对 auto 的重新定义代表了C和C ++之间的另一种实质性区别.)

(In C++11 and later, auto instructs the compiler to deduce the type. sum will be a float with value 3.14f + 1. Compiling as C++98 or C++03 may still work, but generate a warning about C++11 extensions. This is what clang does, for example. This re-defining of auto in C++11 represents another material divergence between C and C++.)

这篇关于为什么一个整数和一个浮点数之和是一个整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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