3.2. Converting from double
to int
¶
As I mentioned, C++ converts int
s to double
s automatically if necessary,
because no information is lost in the translation. On the other hand,
going from a double
to an int
requires rounding off. C++ doesn’t perform
this operation automatically, in order to make sure that you, as the
programmer, are aware of the loss of the fractional part of the number.
The simplest way to convert a floating-point value to an integer is to use a typecast. Typecasting is so called because it allows you to take a value that belongs to one type and “cast” it into another type (in the sense of molding or reforming, not throwing).
The syntax for typecasting is like the syntax for a function call. For example:
double pi = 3.14159;
int x = int (pi);
The int function returns an integer, so x gets the value 3. Converting to an integer always rounds down, even if the fraction part is 0.99999999.
For every type in C++, there is a corresponding function that typecasts its argument to the appropriate type.
- temp
- This is the name of a variable. Only the value of a variable will print with cout.
- 8
- Remember that converting to an integer always rounds down.
- 7
- Correct!
- 8.0
- This is not an integer data type, and it's not the right number.
- 7.0
- This is not an integer data type.
Q-1: In the lab, we measured a temperature of 7.99999999 degrees C, using an extremely precise measuring device. Now we are writing a program to perform some calculations with our data. Consider the following C++ code.
int main () {
double temp = 7.99999999;
int roundedTemp = int (temp);
cout << roundedTemp;
}
What is the value of roundedTemp?
Method 1:
final
is adouble
, meaning my final grade will have more digits past the decimal, and will be higher than theint
in Method 2.-
Although
final
is adouble
, it doesn’t have any digits past the decimal due to the integer division. Method 1: the rounding happens at the beginning, so all three of my test scores will be rounded to the nearest
int
, which in my case, will round all of them up.-
Converting to an
int
always rounds down, even if yourdouble
is very close to the next integer. Method 2:
final
is anint
, so it gets rounded up.-
Converting to an
int
always rounds down, even if yourdouble
is very close to the next integer. Method 2: the rounding happens at the very end, so my grade will be higher!
-
Always save your rounding until the end!
Q-2: Your final grade consists of your average performance on exam 1 and exam 2. Your professor is using C++ to grade the exams and allows you to choose which method you’d like your exam to be graded.
double exam1 = 88.8;
double exam2 = 72.7;
double exam3 = 97.9;
Method 1:
double final = (int(exam1) + int(exam2) + int(exam3)) / 3;
Method 2:
int final = int((exam1 + exam2 + exam3) / 3);
Which method would you choose and why?