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

标签 c++ types casting g++ narrowing

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

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 头文件 段落 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/

相关文章:

f# - 由于循环引用,确定如何订购 F# 类型的问题

javascript - 是否可以将整数作为键存储在 javascript 对象中?

php - 有没有办法从 PHP 中的 boolean 值中获取 "true"/"false"字符串值?

swift - swift 中两个 'identical' 类型之间隐式转换

c# - 为什么这个转换不起作用?

c++ - 在使用有效的 C++ 时赋值吗?

c++ - 编译器如何知道如何递增不同的指针?

c++ - 具有友好方法名称的 c 静态方法调用

c++ - 将捕获的 lambda 作为函数指针传递

python 在运行时创建一个包含另一个类的类