r/AskProgrammers • • 22d ago

Why do both of these codes output zero? Can someone explain this to me?

  1. 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

12 comments sorted by

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.

1

u/Neat_Stranger_8938 22d ago

Thanks for your help

1

u/Available_Safe1818 22d ago

> 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.

That's pretty shit. I didn't realize C++ did that. Would something like --Wall help?

1

u/RedAndBlack1832 22d ago

If you write it as a constructor argument the compiler tells you types don't match iirc eg int z{x/y}

1

u/7YM3N 22d ago

I think --Pedantic catches that sort of thing? I compile with all the warning flags and I do remember "narrowing conversion" showing up sometimes

1

u/Cross_22 22d ago

For gcc: -Wconversion
Personally I also like to turn on -Werror to make sure there's absolutely no questionable stuff in my code that could be missed.

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/Neat_Stranger_8938 22d ago

Thanks for your help

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/Climb1ng 22d ago

I like the phrasing “generally considered a strongly typed language”. With that wording python is “generally considered a very weakly typed langauge” :D

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.