DevAcademia lesson/C++ Basics
Printing Numbers
Topic progressTopic 6 of 109 - 6% complete
~8 min lesson23 learning blocks4 code examples1 checks/interactions
Lesson outline
Outputting Numeric Values
The std::cout object handles all numeric types in C++ including integers and floating-point numbers, and supports scientific notation.
Key advantages:
- Automatic type conversion to readable format
- No manual memory management needed
- Supports all arithmetic types (
int,long long,float,double, etc.)
Basic Number Output
Printing different numeric types:
Mathematical Expressions
std::cout prints the result of expressions (evaluated with normal operator precedence):
Advanced Formatting
Use manipulators to control precision and notation. Flags and precision persist until changed:
Integer Bases & Flags
Control integer base and presentation with stream flags:
Best Practices
For production code:
- Initialize variables before output
- Prefer
'\n'for newlines; reservestd::endl(newline + flush) for when output must be immediately visible - Use constants for magic numbers
- Consider locale-specific formatting where appropriate
- For financial values, prefer fixed notation (
std::fixedwithstd::setprecision(2)) and consider storing values in integer minor units (e.g., cents) to avoid floating-point rounding issues - For clearer booleans, use
std::boolalpha(true/falseinstead of1/0) - Avoid
using namespace std;in global scope; qualify withstd::
Was this topic clear?