是'float a = 3.0;'一个正确的语句? [英] Is 'float a = 3.0;' a correct statement?

查看:153
本文介绍了是'float a = 3.0;'一个正确的语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下声明:

float a = 3.0 ;

是一个错误?我在一本书中看到 3.0 是一个 double 值,我必须将其指定为 float a = 3.0f 。是这样吗?

is that an error? I read in a book that 3.0 is a double value and that I have to specify it as float a = 3.0f. Is it so?

推荐答案

声明不是一个错误float a = 3.0 :如果你这样做,编译器会将double literal 3.0转换为一个浮点数。

It is not an error to declare float a = 3.0 : if you do, the compiler will convert the double literal 3.0 to a float for you.


  1. 由于性能原因:

具体来说,请考虑:

float foo(float x) { return x * 0.42; }

这里,编译器将为每个返回的值发送一个转换要避免它,你应该声明:

Here the compiler will emit a conversion (that you will pay at runtime) for each returned value. To avoid it you should declare:

float foo(float x) { return x * 0.42f; } // OK, no conversion required


  • 例如以下比较失败:

    float x = 4.2;
    if (x == 4.2)
       std::cout << "oops"; // Not executed!
    

    我们可以使用浮点数字符号来修复它:

    We can fix it with the float literal notation :

    if (x == 4.2f)
       std::cout << "ok !"; // Executed!
    

    (注意:当然,

    (Note: of course, this is not how you should compare float or double numbers for equality in general)

    调用正确的重载函数(出于同样的原因):

    示例:

    void foo(float f) { std::cout << "\nfloat"; }
    
    void foo(double d) { std::cout << "\ndouble"; }
    
    int main()
    {       
        foo(42.0);   // calls double overload
        foo(42.0f);  // calls float overload
        return 0;
    }
    


  • 如Cyber​​所述,在类型推导上下文中,有必要帮助编译器推导出 float

  • As noted by Cyber, in a type deduction context, it is necessary to help the compiler deduce a float :

    auto

    auto d = 3;      // int
    auto e = 3.0;    // double
    auto f = 3.0f;   // float
    

    同样,在模板类型扣除的情况下:

    And similarly, in case of template type deduction :

    void foo(float f) { std::cout << "\nfloat"; }
    
    void foo(double d) { std::cout << "\ndouble"; }
    
    template<typename T>
    void bar(T t)
    {
          foo(t);
    }
    
    int main()
    {   
        bar(42.0);   // Deduce double
        bar(42.0f);  // Deduce float
    
        return 0;
    }
    







  • 在线演示

    这篇关于是'float a = 3.0;'一个正确的语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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