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;
// By default, cout shows only 6 significant digits, so both print 3.14159:
cout << f << endl; // Prints: 3.14159
cout << d << endl; // Prints: 3.14159
// d still stores more precision internally; raise the output precision to reveal it:
cout << setprecision(12) << d << endl; // Prints: 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.
Try 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