CPA-21-02 practice question 34 of 35

What is the output of the program given below? #include using namespace std; int main (int argc, const char * argv[]) { float f=?10.501; cout

Full set: 257 questions
Answer options
A: 0
B: 11
C: ?10 Correct answer
D: ?11
Correct Answer:
C. ?10
Explanation

The program initializes a floating-point variable f with the value -10.501. It then uses a C-style cast (int)f to convert the float to an integer before printing it. According to the C++ standard, when a floating-point type is converted to an integer type, the fractional part is discarded (truncated towards zero). Therefore, -10.501 is truncated to -10. (Note: The ? in the snippet is a typographical error for the minus sign -).

Why Incorrect

A. 0 Incorrect because the integer part of the float is -10, not 0.
B. 11 Incorrect because casting to int truncates towards zero; it does not round absolute values up.
D. -11 Incorrect because conversion from float to int truncates towards zero, not towards negative infinity (like floor() would).

References

- ISO/IEC 14882:2017 (C++17 Standard), Section 7.10 [conv.fpint], Floating-integral conversions, paragraph 1.

- Bjarne Stroustrup, "The C++ Programming Language, 4th Edition", Chapter 10.5.2 (Conversions), p. 274.

Scroll to Top