Reputation: 21
Whenever I try to compile I get
24 [Warning] converting to int
from float
83 [Warning] converting to int
from float
int a , b = 8;
float c = 5.2;
float d = 8E3;
a = static_cast<float>(b) * c; // 24
cout << a << "\n";
cout << d << "\n";
int x, y, answer;
x = 7;
y = 9;
answer = 5;
answer *= (x + y);
cout << answer << "\n";
answer *= x + y;
cout << answer << "\n";
float m = 33.97;
answer += (x + y + m); // 83
cout << answer << "\n";
Any suggestions as to what I'm doing wrong?
Upvotes: 2
Views: 8011
Reputation: 52317
Your question seems to be about conversion from float to int, not from int to float.
Basically you are doing nothing wrong. It is only a warning, as the value will be truncated (and maybe you don't expect that). To tell the compiler that you really want to get an int out of a float, you can make the cast explicit, like this:
a = static_cast<int>(static_cast<float>(b) * c);
Then it will not warn you anymore.
Upvotes: 2
Reputation: 680
Well you're just getting a warning since the compiler is changing a floating-point value to an integer, thus truncating the result.
int a;
float f = 3.2;
a = f; // a is 3, a trunctated 3.2
Upvotes: 1
Reputation: 5181
a = static_cast<float>(b) * c;
a
is an int
, and the right-hand side of the equation is the multiplication of two floats
, which will result in an intermediate float
value, which is then implicitly casted to an int
, causing the warning you are seeing.
Also:
answer += (x + y + m);
answer
is an int
type, and so are x
and y
, but m
is float
, again causing the intermediate result of the right-hand side to be a float
.
These conversions will cause truncation of the fractional values of the float
results. You can get rid of the warnings by explicitly casting to an int
:
a = static_cast<int>(static_cast<float>(b) * c);
answer += static_cast<int>(x + y + m);
Upvotes: 5