Reputation: 41
Hi i am a c++ beginner and i really cant get my head around this error conversion from 'double' to 'int' requires a narrowing conversion this is my code; #include "Segment.h" using namespace 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)));
}
}
please someone help thanks
the error i am getting is : error C2397: conversion from 'double' to 'int' requires a narrowing conversion
Upvotes: 1
Views: 13951
Reputation: 6597
The error is caused by your conversion of a double
to int
in the second Segment
constructor. From the context of your code, I would assume that the_end
is defined as an int
, yet you are assigning it a double
.
Segment::Segment(double new_end, double new_acceleration)
: the_end{ new_end }, // <-- Here
acceleration{ new_acceleration }
{
}
Your use of an initializer list in particular is causing the error as they do not allow for narrowing.
Of special note for your situation:
To fix the error, simply provide an explicit cast:
Segment::Segment(double new_end, double new_acceleration)
: the_end{ static_cast<int>(new_end) },
acceleration{ new_acceleration }
{
}
Do note of course the potential dangers of casting from an int
to a double
(integer truncation, potential loss of data from going from 8 bytes to 4 bytes, etc.).
Upvotes: 3