gpt4 book ai didi

c++ - 浮点提升 : stroustrup vs compiler - who is right?

转载 作者:IT老高 更新时间:2023-10-28 12:37:38 25 4
gpt4 key购买 nike

在 Stroustrup 的新书“C++ 编程语言 - 第四版”的第 10.5.1 节中,他说,在执行算术运算之前,整数提升用于从较短的整数类型创建整数,类似地,浮点-点提升用于从 float 中创建 double 。

我使用以下代码确认了第一个声明:

#include <iostream>
#include <typeinfo>

int main()
{
short a;
short b;
std::cout << typeid(a + b).name() << std::endl;
}

用 vc++ 输出“int”,用 gcc 输出“i”。

但是用 float 而不是短裤测试它,输出仍然是“float”或“f”:

#include <iostream>
#include <typeinfo>

int main()
{
float a;
float b;
std::cout << typeid(a + b).name() << std::endl;
}

根据 Stroustrup 的说法,浮点提升规则没有异常(exception),所以我希望输出为“double”或“d”。

上述关于促销的部分是否有误或不清楚? C++98 和 C++11 在类型提升方面有什么不同吗?

最佳答案

我不知道 Stroustrup 的书到底说了什么,但是按照标准,在这种情况下,floats 不会被转换为 doubles。在应用大多数算术二元运算符之前,先应用 5p9 中描述的常用算术转换:

  • If either operand is of scoped enumeration type (7.2), no conversions are performed; if the other operand does not have the same type, the expression is ill-formed.
  • If either operand is of type long double, the other shall be converted to long double.
  • Otherwise, if either operand is double, the other shall be converted to double.
  • Otherwise, if either operand is float, the other shall be converted to float.
  • Otherwise, the integral promotions (4.5) shall be performed on both operands. [...]

整体提升是导致两个 short 转换为 int 的原因。但是两个 float 不会按照这些规则转换为 double 。如果将 float 添加到 doublefloat 将被转换为 double

以上来自C++11。 C++03 包含相同的规则,除了引用范围枚举的规则。

关于c++ - 浮点提升 : stroustrup vs compiler - who is right?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17215484/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com