“auto”关键字是否总是将浮点值评估为双精度?

Bor*_*isV 2 c++ auto

继续这个已关闭的问题: C++:“auto”关键字影响数学计算?

正如人们建议的那样,我通过向浮点值添加“f”后缀来修改代码。

#include <cmath>
unsigned int nump=12u;
auto inner=2.5f;
auto outer=6.0f;
auto single=2.f*3.14159265359f/nump;
auto avg=0.5f*inner+0.5f*outer;
for (auto i=0u;i<nump;++i){
    auto theta=i*single;
    auto px=avg*sin(theta);
    auto py=avg*cos(theta);
    auto tw=17.f;
    int v1=std::round(1.f+px-tw/2.0f);
    int v2=std::round(2.f+py-tw/2.0f);
    std::cout<<"#"<<i<<":"<<v1<<";"<<v2<<std::endl;
}
Run Code Online (Sandbox Code Playgroud)

相对

#include <cmath>
unsigned int nump=12u;
float inner=2.5f;
float outer=6.0f;
float single=2.f*3.14159265359f/nump;
float avg=0.5f*inner+0.5f*outer;
for (unsigned int i=0u;i<nump;++i){
    float theta=i*single;
    float px=avg*sin(theta);
    float py=avg*cos(theta);
    float tw=17.f;
    int v1=std::round(1.f+px-tw/2.0f);
    int v2=std::round(2.f+py-tw/2.0f);
    std::cout<<"#"<<i<<":"<<v1<<";"<<v2<<std::endl;
}
Run Code Online (Sandbox Code Playgroud)

结果完全相同 - 两个版本之间的输出不同。那么这是否意味着“auto”总是将浮点值计算为“double”类型?

Kon*_*lph 8

问题是您的代码正在使用::sin而不是std::sin(与 相同cos)。也就是说,您\xe2\x80\x99正在使用sin在全局命名空间中找到的函数。

\n

std::sin已超载float。但::sin不是\xe2\x80\x99t,并且它总是返回a double(因为::sin是遗留的C函数,而C没有\xe2\x80\x99t函数重载)。

\n

在代码中使用std::sinandstd::cos来解决问题。

\n