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.
To fix this, append f
to each of your constants, eg 0.5f
.
conversion from 'double' to 'float' requires a narrowing conversion
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.