JuniorCodeOccasionalNot answered yet
What do 5 / 2, 5.0 / 2, and 7 % 3 print?
Predict the output of this line.
std::cout << 5 / 2 << " " << 5.0 / 2 << " " << 7 % 3;
Determine the output and explain.
2 2.5 1. 5 / 2 is integer division and truncates toward zero. 5.0 / 2 promotes the int to double, giving 2.5. % is the integer remainder. Note -7 % 3 is -1 in C++ — the result's sign follows the dividend.
- ✗Expecting
5 / 2to give2.5because the math result is fractional - ✗Thinking
%rounds the quotient instead of returning the remainder - ✗Assuming
-7 % 3is2— in C++ the sign follows the dividend, so it is-1
- →What does
-7 % 3evaluate to in C++ and why? - →How do you force floating-point division between two
intoperands?