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

C Programming Floating Point Issues Difficulty: Easy
Choose an option
  • A
    0
  • B
    0.0
  • C
    7.0
  • D
    7
  • E
    None of the above

Answer

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

Discussion & Comments
No comments yet. Be the first to comment!
More Questions from Floating Point Issues
Join Discussion