Bird
0
0

Why does the following MATLAB code produce the string 'Value: 3.14' instead of 'Value: 3.140' when using sprintf?

hard📝 Conceptual Q10 of 15
MATLAB - String Handling
Why does the following MATLAB code produce the string 'Value: 3.14' instead of 'Value: 3.140' when using sprintf?
str = sprintf('Value: %.3g', 3.14);
ABecause %.3g rounds to two decimals automatically
BBecause %g always truncates decimals
CBecause %g uses the shortest representation, not fixed decimals
DBecause %.3g is invalid syntax
Step-by-Step Solution
Solution:
  1. Step 1: Understand %g specifier behavior

    %g chooses shortest representation between %f and %e.
  2. Step 2: Analyze output for 3.14 with %.3g

    It shows 3 significant digits, so '3.14' instead of fixed 3 decimals.
  3. Final Answer:

    Because %g uses the shortest representation, not fixed decimals -> Option C
  4. Quick Check:

    %g = shortest representation, not fixed decimals [OK]
Quick Trick: Use %f for fixed decimals, %g for shortest form [OK]
Common Mistakes:
  • Expecting %g to fix decimal places
  • Confusing %g with %f
  • Thinking %.3g is invalid

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More MATLAB Quizzes