Get a floating point value and print the floating point value without any trailing zeros.
The Real-World Lesson
This problem teaches an important programming principle: when your current toolset is limited, sometimes borrowing from related technologies is the smartest solution!
cout
and iomanip
), removing trailing zeros
is surprisingly difficult. But C's printf
has a built-in format specifier
(%g
) that does this automatically! This is a perfect example of pragmatic
programming.
The %g
specifier is magical for this task:
Input | With %f | With %g |
---|---|---|
23.0900 |
23.090000 |
23.09 |
12.5200 |
12.520000 |
12.52 |
100.0 |
100.000000 |
100 |
0.00056 |
0.000560 |
0.00056 |
Feature | C Style | C++ Style |
---|---|---|
Input | scanf("%lf", &num) |
cin >> num |
Output | printf("%g", num) |
cout << num |
Header | <cstdio> |
<iostream> |
Type Safety | ❌ No (manual format) | ✅ Yes (automatic) |
Trailing Zeros | ✅ Easy with %g | ❌ Complex |
double num;
scanf("%lf", &num); // %lf = long float (double)
// & = address-of operator
// %f - Fixed decimal (6 decimals default)
// %e - Scientific notation
// %g - Shortest representation (removes trailing zeros!)
// %lf - For double in scanf (not printf)
scanf
needs the memory address to store the value:
double num;
scanf("%lf", &num); // & gives memory location
// scanf writes directly to that location
// Without & it would pass the value (wrong!)
// With & it passes the address (correct!)
scanf/printf
with cin/cout
in same program (buffering issues)For reference, here's the complex C++ way (you don't need this for basic problems!):
// Complex C++ approach (avoid for beginners)
double num;
cin >> num;
string str = to_string(num);
// Remove trailing zeros manually...
// Much more code needed!
%g
automatically removes trailing zeros - perfect for this task!scanf
needs &
to get the variable's addressprintf
offers powerful format control100.0 → 100
(decimal point removed too!)
0.00560 → 0.0056
(trailing zero removed)
3.14159 → 3.14159
(no trailing zeros to remove)
#include <cstdio>
int main() {
double num;
// scanf: C-style input
// %lf = long float (double)
// &num = address where to store the value
scanf("%lf", &num);
// printf with %g: Smart formatting!
// - Removes trailing zeros automatically
// - Removes trailing decimal if no fraction
// - Uses shortest representation
printf("%g\n", num);
return 0;
}