简体   繁体   English

从“double”到“float”的转换需要缩小转换

[英]conversion from 'double' to 'float' requires a narrowing conversion

I have the following lines of code:我有以下代码行:

std::vector<float> qualities = { 0.5, 0.6, 0.7, 0.8 };
std::vector<float> percentages = { 0.15, 0.16, 0.17, 0.18 };

I get the error mentioned in the title for each element.我得到了每个元素的标题中提到的错误。 Why is that?这是为什么?

You get the message because a constant of the form (eg) 0.5 is a double , and assigning a double to a float is a narrowing conversion.您收到消息是因为0.5形式的常量是double ,而将double分配给float是缩小转换。

To fix this, append f to each of your constants, eg 0.5f .要解决此问题,请将 append f设为您的每个常量,例如0.5f

conversion from 'double' to 'float' requires a narrowing conversion从“double”到“float”的转换需要缩小转换

I get the error mentioned in the title for each element.我得到了每个元素的标题中提到的错误。 Why is that?这是为什么?

Because you are constructing a vector of floats using double literals.因为您正在使用双文字构造浮点向量。 Such conversion is narrowing.这种转换正在缩小。

That said, such conversions are allowed in this context and the example is well-formed and should compile.也就是说,在此上下文中允许进行此类转换,并且该示例格式正确,应该可以编译。 I suspect that you've used some compiler options to ask the compiler to not compile some well-formed programs.我怀疑您使用了一些编译器选项来要求编译器不要编译一些格式良好的程序。

You can write a float literal by appending f to a double literal.您可以通过将f附加到 double 文字来编写 float 文字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM