Back to questionsWhat do
JuniorCodeOccasional
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, truncating toward zero. In 5.0 / 2 the int is converted to double (a usual arithmetic conversion, not a promotion): 2.5. % is the remainder; -7 % 3 is -1.
- 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?