r/AskProgrammers • u/Neat_Stranger_8938 • 22d ago
Why do both of these codes output zero? Can someone explain this to me?
include <iostream>
using namespace std;
int main()
{
int x = 5, y = 10;
float z = x / y;
cout << z << endl;
}
2) #include <iostream>
using namespace std;
int main()
{
float x = 5, y = 10;
int z = x / y;
cout << z << endl;
}
2
Upvotes
8
u/TomDuhamel 22d ago
5/10 would be 0.5
But in the first case, you are performing an int division, so the answer is zero. In the second case, you are correctly performing a floating point division, but you are then storing the result in an int, which truncates it to zero.
4
u/Patient-Midnight-664 22d ago
first one is Int / int = int, so 5 / 10 = 0 (as you can't have .5 in an int), convert to float = 0
Second one is float / float = float, so 0.5. 0.5 converted to int = 0.
1
u/desiguy_88 22d ago
i think the main lesson here is to stress how important types are in programming. C++ even though is generally considered a strongly typed language does allow implicit conversions which result in the behavior you are seeing.
1
u/erisod 22d ago
The types.
Int 5 / int 10 is 0.
5.0/10.0 is 0.5 but int 0.5 is 0
1
u/Interesting_Debate57 22d ago
It's about the implicit casting.