由于某种原因,我收到以下警告
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::sin和 std::cos代替 sin
和 cos
,以便您获得正确重载的版本。你可以看到差异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
头文件 段落 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/