What is printed after casting a float to int in C?\n\n#include<stdio.h>\nint main()\n{\n float fval = 7.29;\n printf("%d\n", (int)fval);\n return 0;\n}\n\nAssume standard C semantics for casts and printf.

Difficulty: Easy

Correct Answer: 7

Explanation:


Introduction / Context:
Casting from float to int truncates toward zero. Printing with %d expects an int value. This question checks understanding of truncation versus rounding.



Given Data / Assumptions:

  • fval = 7.29 (positive float).
  • (int)fval discards the fractional part.
  • printf("%d") prints the resulting integer in decimal.


Concept / Approach:
Use the truncation rule: for positive numbers, truncation is equivalent to floor; for negative numbers, truncation differs from floor.



Step-by-Step Solution:
Compute (int)7.29 → 7.printf prints 7.



Verification / Alternative check:
Testing with a negative value, e.g., (int)(-7.29) would yield -7 (truncation), whereas floor(-7.29) would be -8.



Why Other Options Are Wrong:
0, 0.0, 7.0: not consistent with truncation and %d formatting.



Common Pitfalls:
Confusing rounding with truncation; using the wrong printf format specifier.



Final Answer:
7

More Questions from Floating Point Issues

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion