Real Numbers
Part of the Fundamentals section of Coddy's C++ journey — lesson 6 of 74.
In C++, real numbers are typically represented using two main data types: float and double.
float is used to store numbers with a decimal point. For example:
float price = 99.99f;The 'f' (or 'F') at the end of a decimal number is called a literal suffix, and it explicitly tells the compiler that this number should be treated as a float.
double is used to store numbers with a decimal point, but with double precision. float typically has 7 decimal digits of precision whereas double typically has 15-17 decimal digits of precision. For example:
float f = 3.14159265359;
double d = 3.14159265359;
cout << f << endl; // Might print: 3.14159
cout << d << endl; // Might print: 3.14159265359Challenge
BeginnerWrite a C++ program that declares and initializes the following variables:
- Declare a
floatvariable nameditemPriceand initialize it with the value24.99f. - Declare a
doublevariable namedtemperatureand initialize it with the value23.5.
Cheat sheet
In C++, real numbers are represented using float and double data types.
float stores decimal numbers with single precision (typically 7 decimal digits):
float price = 99.99f;The 'f' suffix explicitly tells the compiler to treat the number as a float.
double stores decimal numbers with double precision (typically 15-17 decimal digits):
float f = 3.14159265359;
double d = 3.14159265359;
cout << f << endl; // Might print: 3.14159
cout << d << endl; // Might print: 3.14159265359Try it yourself
#include <iostream>
int main() {
// Declare and initialize variables here
// Output the values
std::cout << "Price: " << itemPrice << std::endl;
std::cout << "Temperature: " << temperature << std::endl;
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison3Variables Part 2
Type DeclarationNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementConditional OperatorRecap - If ElseNested If - Else