gpt4 book ai didi

c++ - float 到双重误解???克++

转载 作者:搜寻专家 更新时间:2023-10-31 01:07:38 24 4
gpt4 key购买 nike

出于某种原因,我收到以下警告

filename.cpp:99:53: warning: narrowing conversion of ‘sin(((double)theta))’ from ‘double’ to ‘float’ inside { } [-Wnarrowing]
filename.cpp:99:66: warning: narrowing conversion of ‘cos(((double)theta))’ from ‘double’ to ‘float’ inside { } [-Wnarrowing]

这听起来像是在尝试使用“double cos(double)”等而不是“float cos(float)”等。我一直在想更多的方法来向编译器提出这个建议,但没有取得任何进展。我该怎么做才能解决这个问题?

void foo(float theta)
{
theta = (float)M_PI*theta/180.0f;
MyClass variable = { 1.0f, 0.0f, 0.0f, 0.0f,
0.0f, cos(theta), -sin(theta), 0.0f,
0.0f, sin(theta), cos(theta), 0.0f,
0.0f, 0.0f, 0.0f, 1.0f };
bob = variable;
}

谢谢


编辑:将其更改为此会使警告消失,但我仍然想知道问题出在哪里

float C = cos(theta), S = sin(theta);
MyClass variable = { 1.0f, 0.0f, 0.0f, 0.0f,
0.0f, C, -S, 0.0f,
0.0f, S, C, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f };

最佳答案

您需要使用 std::sinstd::cos代替 sincos 以便您将获得正确重载的版本。你可以看到差异live :

MyClass variable = { 1.0f,    0.0f,         0.0f,   0.0f,
0.0f, std::cos(theta), -std::sin(theta), 0.0f,
0.0f, std::sin(theta), std::cos(theta), 0.0f,
0.0f, 0.0f, 0.0f, 1.0f };

unspecified behavior C 库 中的函数是否首先在全局命名空间中声明 C++ 草案标准部分 17.6.1.2 Headers 段落 4 说(强调我的):

Except as noted in Clauses 18 through 30 and Annex D, the contents of each header cname shall be the same as that of the corresponding header name.h, as specified in the C standard library (1.2) or the C Unicode TR, as appropriate, as if by inclusion. In the C++ standard library, however, the declarations (except for names which are defined as macros in C) are within namespace scope (3.3.6) of the namespace std. It is unspecified whether these names are first declared within the global namespace scope and are then injected into namespace std by explicit using-declarations (7.3.3).

因此,如果 C 库 函数位于全局命名空间中,您将获得 cos 的版本和 sin这只需要 double,这与我们看到的行为一致。

关于c++ - float 到双重误解???克++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19123631/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com