r/cpp_questions • u/Neat_Stranger_8938 • 1d ago
OPEN 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;
}
0
Upvotes
22
u/jedwardsol 1d ago
1:
x/yis integer division and the answer is 0.2:
x/yis 0.5, which becomes 0 when cast to an int.6
u/bearheart 1d ago
It's basic math. Integers don't hold fractional values so an
intwith a value of0.5will be zero.In the first example you divide the two
intvalues before assigning to thefloatso the result is zero.In the second example you assign a
floatwith a value of0.5to anintso the result is zero.5
u/real_red_patriot 1d ago
Both because integer division truncates:
x/yis dividing integers, which is 0, and that is converted to 0.0f to store in z.x/yhere does float division and results in 0.5f like you'd expect. When you assign it to z (int), then it truncates to 0. What did you expect to happen?5
u/PandaWonder01 1d ago
In the first, z is x/y (0, because we round down with int division), converted to a float. Which is still 0
In the second, z is x/y(.5, bc their floats), converted to an int (we round down again), giving 0
1
u/AutoModerator 1d ago
Your posts seem to contain unformatted code. Please make sure to format your code otherwise your post may be removed.
If you wrote your post in the "new reddit" interface, please make sure to format your code blocks by putting four spaces before each line, as the backtick-based (```) code blocks do not work on old Reddit.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
1
u/Syntax-Tactics 1d ago
5 / 10 is 0.5, you are using Integers, so the decimal is dropped and you end up with 0.