为什么不是“0f”在C ++中被视为浮点文本? [英] Why isn't "0f" treated as a floating point literal in C++?

查看:139
本文介绍了为什么不是“0f”在C ++中被视为浮点文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在C ++中将 0f 视为浮点文本?

Why isn't 0f treated as a floating point literal in C++?

#include <iostream>

using namespace std;

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

  return 0;
}

编译上面的代码给我


使用VS2008的C2509(语法错误:数字上的错误后缀)

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



using VS2008.

推荐答案

如果有明确说明的原因,这个设计决定,将在C99​​原理文档这个东西逐字从C没有重新考虑它)。但没有。这是关于'f'后缀的所有内容:

If there was an explicitly stated reason for this design decision, it would be in the C99 "Rationale" document (C++ copied all this stuff verbatim from C without reconsidering it). But there isn't. This is everything that's said about the 'f' suffix:


§6.4.4.2浮动常量



与现有实践一致,浮点常量定义为
类型 double 。由于C89允许在 float float 操作数
的表达式c $ c> 的方法
表示显式 float 常量。 long double 类型
会引发类似问题。

§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.

> F L
浮动常量,很像长整型的 L 后缀。默认的
类型的浮动常数保持双倍以兼容以前的做法。
小写 f l

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.

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

There is an implied reason, though. Note the wording: "the ... suffixes have been added to convey type information with floating constants." The authors of the standard were thinking of numeric constants as already being unambiguously either integer or floating point by the time you get to the suffix. The suffix is only for extra specificity within the category, it can't flip a number from one category to another. This is backed up by the actual grammar (C99 §6.4.4) which first defines numeric constants as being either integer-constants or floating-constants, and then defines separate classes of suffixes for each.

这篇关于为什么不是“0f”在C ++中被视为浮点文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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