c++ - 为什么 "0f"在 C++ 中不被视为浮点文字?

标签 c++ syntax floating-point syntax-error notation

为什么 0f 在 C++ 中不被视为浮点字面量?

#include <iostream>

using namespace std;

int main(){
  cout << 0f << endl;

  return 0;
}

编译上面给了我

C2509 (syntax error: 'bad suffix on number')

使用 VS2008。

最佳答案

如果此设计决策有明确说明的原因,则应在 C99“基本原理”文档中(C++ 从 C 中逐字复制所有这些内容,而没有重新考虑)。但是没有。这就是关于“f”后缀的所有内容:

§6.4.4.2 Floating constants

Consistent with existing practice, a floating-point constant is defined to have type double. Since C89 allows expressions that contain only float operands to be performed in float arithmetic rather than double, a method of expressing explicit float constants is desirable. The long double type raises similar issues.

The F and L suffixes have been added to convey type information with floating constants, much like the L suffix does for long integers. The default type of floating constants remains double for compatibility with prior practice. Lower-case f and l are also allowed as suffixes.

不过,一个隐含的原因。请注意措辞:“已添加 ... 后缀以使用 float 常量传达类型信息。”该标准的作者认为数字常量在您到达后缀时已经明确地是整数或 float 。后缀仅用于类别内的额外特异性,它不能将数字从一个类别翻转到另一个类别。这得到了实际语法(C99 §6.4.4)的支持,该语法首先将数字常量定义为整数常量或浮点常量,然后定义单独的类每个的后缀。

关于c++ - 为什么 "0f"在 C++ 中不被视为浮点文字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3961467/

相关文章:

c++ - 使用本地 ipv6 套接字将 UDP 发送到本地 ipv4 地址

C++ 如何逐字打印 .txt 文件?

ruby - 在条件中声明变量

c++ - 使用 C++,有没有办法检测编译器/系统是否将 floats/doubles 非规范化为 "normalized"?

c++ - 使用 epsilon 将 double 与零进行比较

java - 与 NaN 不同,为什么浮点无穷大是相等的?

c++ - 使用 C++ 在编译时操作变量

c++ - 删除命令提示符

powershell - 如何在Powershell中简化命令

typescript - 如何通过指定每个属性及其值来实例化 TypeScript 中的对象?