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).
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.
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.
Although final is a double, 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.