C++ Print Numbers
In this page:
Printing Numeric Literals
cout << can print numeric literals directly, without any conversion, and will display the number exactly as written, whether it's a whole integer or a decimal value.
Example: Printing Numeric Literals
#include <iostream>
int main() {
std::cout << 42 << std::endl;
std::cout << 3.14 << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Printing Arithmetic Results
When cout is given a mathematical expression, C++ evaluates that expression completely first and only then prints the single resulting number, not the original expression text.
Example: Printing Arithmetic Results
#include <iostream>
int main() {
std::cout << 5 + 3 << std::endl; // prints 8, not "5 + 3"
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Printing Different Number Types
cout << works with every numeric type in C++ -- short, int, long, float, and double -- and prints each one formatted according to that type's own conventions.
Example: Printing Different Number Types
#include <iostream>
int main() {
short s = 10;
int i = 1000;
long l = 100000L;
float f = 1.5f;
double d = 3.14159;
std::cout << s << " " << i << " " << l << " " << f << " " << d << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Concatenating Numbers with Text
The << operator can be chained multiple times in a single cout statement, mixing string literals and numeric values, and any number combined this way is automatically converted to its printable text form.
Example: Concatenating Numbers with Text
#include <iostream>
int main() {
int score = 95;
std::cout << "Score: " << score << " out of 100" << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Formatting Numbers in Output
For more control over how a number appears, the iomanip library provides manipulators like setprecision and fixed for a fixed number of decimal places, and setw for a minimum field width.
Example: Formatting Numbers in Output
#include <iostream>
#include <iomanip>
int main() {
double price = 19.5;
std::cout << std::fixed << std::setprecision(2) << price << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: