【问题标题】:Why cannot you use a 'f' suffix directly after an integer?为什么不能在整数后直接使用“f”后缀?
【发布时间】:2020-03-29 09:09:18
【问题描述】:

在编写 C++ 应用程序时,我发现我无法使用 f 后缀(例如 3f),因为 Visual Studio 向我显示以下错误:“未找到文字运算符”。当然,当我使用.f 后缀(例如3.f)时,问题就消失了。这是为什么呢?

【问题讨论】:

  • 你在写什么C++代码?
  • @nick 以任何方式支持您的论点的唯一答案是错误的。其他人都说没有.f这样的东西。
  • 旁白:f 在这里不是文字,而是后缀

标签: c++ floating-point integer


【解决方案1】:

这是standard的规则:

floating-point-literal:
    decimal-floating-point-literal
    hexadecimal-floating-point-literal

decimal-floating-point-literal:
    fractional-constant exponent-part-opt floating-point-suffix-opt
    digit-sequence exponent-part floating-point-suffix-opt

fractional-constant:
    digit-sequence-opt . digit-sequence
    digit-sequence .

exponent-part:
    e sign-opt digit-sequence
    E sign-opt digit-sequence

floating-point-suffix: one of
    f  l  F  L

如您所见,如果没有指数部分,. 必须始终包含在十进制浮点常量中。

K&R 书中对此进行了解释:

浮点常量包含小数点 (123.4) 或指数 (1e-2) 或两者;它们的类型是双精度的,除非后缀。后缀 f 或 F 表示浮点常数; l 或 L 表示长双精度。

因此,我们的想法是,fl 将已经是浮点常量 (double) 修改为具有 floatlong double 的类型。后缀本身不会使非浮点常量变为浮点常量。

【讨论】:

  • 最后一部分是关键:“后缀本身不会使非浮点常量变为浮点常量。”
【解决方案2】:

为什么不能在整数后直接使用“f”字面量?

如果fsuffix在文本形成整数后被允许成为浮点数,十六进制整数/浮点数会出现问题

0x1.23f  // this is a float
0x1p23f  // this is a float
0x123f   // If this now a float?  No, it remains an integer.

f 后缀将浮点文字的类型从默认的double 更改。在 C 语言中,fF 后缀不是浮点 literal,而是浮点 constant

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多