This means a floating-point number with 2 digits after the decimal point, padded with zeros if needed.
Step 2: Apply formatting to 3.14159
Rounded to 2 decimals, 3.14159 becomes 3.14, no extra zero padding before the number.
Final Answer:
Value: 3.14 -> Option B
Quick Check:
%.2f rounds float to 2 decimals = Value: 3.14 [OK]
Hint: %.2f rounds float to 2 decimals in sprintf [OK]
Common Mistakes:
Expecting full decimal without rounding
Confusing zero padding before decimal
Ignoring rounding rules
4. Identify the error in this MATLAB code:
str = sprintf('Name: %s, Age: %d', 25, 'John');
medium
A. sprintf cannot format multiple variables
B. Missing semicolon at the end
C. Incorrect format specifier for string
D. The order of variables does not match format specifiers
Solution
Step 1: Check format specifiers and variable order
The format expects a string first (%s) then an integer (%d), but variables are 25 (int) then 'John' (string).
Step 2: Identify mismatch cause
Variables are swapped, causing wrong data types for specifiers.
Final Answer:
The order of variables does not match format specifiers -> Option D
Quick Check:
Variable order must match specifiers = A [OK]
Hint: Match variable order exactly to format specifiers [OK]
Common Mistakes:
Swapping variable order
Ignoring type mismatch
Assuming sprintf auto-corrects order
5. You want to create a formatted string showing a product name and price with 2 decimals, like "Product: Laptop, Price: $999.99". Which sprintf call correctly formats name = 'Laptop' and price = 999.987?
hard
A. sprintf('Product: %s, Price: $%0.2f', name, price)
B. sprintf('Product: %s, Price: $%d', price, name)
C. sprintf('Product: %s, Price: $%f', name, price)
D. sprintf('Product: %s, Price: $%.2d', name, price)
Solution
Step 1: Identify correct format specifiers
%s for string name, %0.2f for float price with 2 decimals.
Step 2: Check variable order and formatting
sprintf('Product: %s, Price: $%0.2f', name, price) uses correct order and formats price to 2 decimals, rounding 999.987 to 999.99.
Final Answer:
sprintf('Product: %s, Price: $%0.2f', name, price) -> Option A
Quick Check:
String + float with 2 decimals = B [OK]
Hint: Use %s for strings and %0.2f for 2-decimal floats [OK]
Common Mistakes:
Swapping variable order
Using %d for floats
Using incorrect precision specifier
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.