C++ constructor prints a character from a float via char(yy): what appears on the console?
#include
class CuriousTab {
int x;
public:
CuriousTab(int xx, float yy) { cout << char(yy); }
};
int main() {
CuriousTab *p = new CuriousTab(35, 99.50f);
return 0;
}
-
A99
-
BASCII value of 99
-
CGarbage value
-
D99.50
Answer
Correct Answer: ASCII value of 99
Explanation
Introduction / Context: The constructor converts a float to char and streams it to cout. In standard C++ streaming, writing a char outputs the corresponding character, not the numeric code. Here, 99.50f is converted to an implementation-defined char by truncation toward zero (commonly 99), which corresponds to the ASCII character 'c'.
Given Data / Assumptions:
- yy = 99.50f; char(yy) converts to a char with code approximately 99.
- cout << char outputs the character itself.
- No newline or numeric formatting is applied.
Concept / Approach: Numeric to char conversion takes the integer part of the float (implementation-defined if outside range; within range here) and interprets that code as a character. ASCII 99 corresponds to 'c', so the visible console output is the single character c (not "99" or "99.50").
Step-by-Step Solution:
Compute char(99.50f) → code 99 → character 'c'.cout << char → prints 'c'.No additional text printed.Verification / Alternative check: Replacing cout << char(yy) with cout << int(yy) would print 99 numerically; using cout << yy would print 99.5 with default formatting.
Why Other Options Are Wrong:
- 99 / 99.50: numeric printing, which is not what cout does for char.
- Garbage value: the value is well-defined and within range.
Common Pitfalls: Expecting cout to display the numeric code when streaming a char; forgetting that casting to unsigned char and then to int is required to print the code number portably.
Final Answer: ASCII value of 99