错误 83 错误 C2398:从 'double' 到 'float' 的转换需要收缩转换
Error 83 error C2398: conversion from 'double' to 'float' requires a narrowing conversion
我找到了很多关于这个错误的帖子,但我可以找到克服它的方法。
这是触发错误的代码:
void main(){
float f{1.3};
}
为什么在初始化列表中没有像任何其他变量那样发生转换?例如,这可以顺利运行:
float f = 1.3;
既然是C++,就不要用c风格的强制转换,试试:
static_cast<float>(std::abs(...))
您评论说使用 1.3
会导致您的编译器出错。这意味着您发现了一个编译器错误。标准很明确,这不是收缩转换,所以应该允许。
引用 N4140(大致为 C++14):
8.5.4 List-initialization [dcl.init.list]
7 A narrowing conversion is an implicit conversion
[...]
-- (7.2) from long double
to double
or float
, or from double
to float
, except where the source is a constant expression and the actual value after conversion is within the range of values that can be represented
(even if it cannot be represented exactly), or
[...]
您的 1.3
是 float
范围内的常量表达式。
我建议向 Microsoft 报告此问题,前提是这还不是已知问题。不幸的是,简单地升级您的 Visual Studio 并不能解决这个问题。我可以在 VS2015 中重现该问题。
这可能是一个错误或其他问题。改用这个:
float f;
f=1.3;
使用 'f' 后缀强制它为浮点数可避免缩小转换。以下作品..
float f{1.3f}
但我同意编译器应该处理它..(根据@hvd 引用的标准)
我找到了很多关于这个错误的帖子,但我可以找到克服它的方法。 这是触发错误的代码:
void main(){
float f{1.3};
}
为什么在初始化列表中没有像任何其他变量那样发生转换?例如,这可以顺利运行:
float f = 1.3;
既然是C++,就不要用c风格的强制转换,试试:
static_cast<float>(std::abs(...))
您评论说使用 1.3
会导致您的编译器出错。这意味着您发现了一个编译器错误。标准很明确,这不是收缩转换,所以应该允许。
引用 N4140(大致为 C++14):
8.5.4 List-initialization [dcl.init.list]
7 A narrowing conversion is an implicit conversion
[...]
-- (7.2) from
long double
todouble
orfloat
, or fromdouble
tofloat
, except where the source is a constant expression and the actual value after conversion is within the range of values that can be represented (even if it cannot be represented exactly), or[...]
您的 1.3
是 float
范围内的常量表达式。
我建议向 Microsoft 报告此问题,前提是这还不是已知问题。不幸的是,简单地升级您的 Visual Studio 并不能解决这个问题。我可以在 VS2015 中重现该问题。
这可能是一个错误或其他问题。改用这个:
float f;
f=1.3;
使用 'f' 后缀强制它为浮点数可避免缩小转换。以下作品..
float f{1.3f}
但我同意编译器应该处理它..(根据@hvd 引用的标准)