从'double'转换为'int'需要缩小转换范围

conversion from 'double' to 'int' requires a narrowing conversion

本文关键字:转换 缩小 范围 int double      更新时间:2023-10-16

嗨,我是一个C 初学者,我真的无法解决这个错误从"双"转换为" int"需要缩小转换这是我的代码; #include" segment.h" 使用名称空间IMAT1206;

Segment::Segment(int new_speed_limit
, int new_end, double new_length, double new_deceleration)
:the_speed_limit{ new_speed_limit }
, the_end{ new_end }
, the_length{ new_length }
, deceleration{ new_deceleration }

{}
Segment::Segment(double new_end, double new_acceleration)
    :the_end{ new_end }
    , acceleration{ new_acceleration }
{} error here 
double Segment::to_real() const {
return static_cast<double>((the_end)*(the_end) / (2 * (the_length)));
while (acceleration)
{
    (acceleration >= 0);
        return static_cast<double> ((the_end) /(1 * (acceleration)));
}
}

请有人帮助谢谢
我遇到的错误是:错误C2397:从"双"转换为" int"需要缩小转换

该错误是由您在第二个Segment构造函数中将double转换为int引起的。从代码的上下文中,我认为the_end定义为int,但您将其分配为double

Segment::Segment(double new_end, double new_acceleration)
  : the_end{ new_end },               // <-- Here
    acceleration{ new_acceleration }
{
}

特别是您对初始化列表的使用导致错误,因为它们不允许缩小。

您情况的特别注释:

  • 浮点值不能转换为整数类型。

要解决错误,只需提供明确的铸件:

Segment::Segment(double new_end, double new_acceleration)
  : the_end{ static_cast<int>(new_end) },
    acceleration{ new_acceleration }
{
}

确实要注意从intdouble的潜在危险(整数截断,从8个字节到4个字节的数据丢失,等等)。