Type Conversions
GOALMove a value correctly between whole and decimal types.

When you divide two whole numbers, C++ throws the fraction away. To get the real answer you must convert one of them to a decimal type first.
ON THIS PAGE
//THE EXAMPLE
#include <iostream>
using namespace std;
int main() {
int total = 7;
int count = 2;
cout << total / count << endl; // 3
cout << (double)total / count << endl; // 3.5
cout << static_cast<double>(total) / count << endl; // 3.5
double price = 9.99;
int rounded = (int)price; // таслаад хаяна, дугуйруулахгүй / cuts, does not round
cout << rounded << endl;
return 0;
}3 3.5 3.5 9
//LINE BY LINE
Watch it run
sum and n are both int, so the division itself is done in whole numbers.
Conversions that happen by themselves
When two different types meet, C++ converts one of them for you — usually towards the type that can hold more.
int a = 3;
double b = 2.5;
double c = a + b; // a нь 3.0 болж хөрвөнө → 5.5
int d = a + b; // 5.5 гарч ирээд таслагдана → 5Converting towards a smaller type loses information silently. The compiler usually only warns.
Converting on purpose
There are two spellings for demanding a conversion. Both work; static_cast is the modern one and is easier to search for.
int sum = 7, n = 2;
double avg1 = (double)sum / n; // 3.5
double avg2 = static_cast<double>(sum) / n; // 3.5Automatic type deduction (auto)
When the type is obvious from the starting value, you can write auto and let the compiler work it out.
auto count = 5; // int
auto price = 19.99; // double
auto letter = 'A'; // char
auto name = string("Bat"); // stringauto requires a starting value. auto x; is an error — there would be nothing to deduce from.
auto shines with long type names. For a plain int it can actually make code harder to read.