Lesson 3 – C++ int to Double – explicit cast

Spread the love

Let’s discuss the c++ int to double and explicit casting. Without the casting a strange kind of math occurs — one that might surprise your math teacher.

int x=1, y=2;

double z;

z = double(x) / y;


/* We look at the double data type 
   it can hold #'s with decimal points
   
   Programmer: Jane Doe
   Cause : C++ Int to Double, explicit cast
   Date : May 2020
*/
 
#include <iostream>
 
using namespace std;
 
int main(){
   double x, y, z;
   x = 3;
   y = 4;
   z = 5;
   cout << "Sending doubles to console\n";
   cout << x << ", " << y << ", " << z;
}
// This compiles just fine
// but this is better x=3.0
// this is better still yet x=3.0f
// No explicit cast

Which Accurately Results in …


c++ into to double coding sample


When to use a double vs float?

A variable type of double is great for large numbers with decimal places

A float uses even more memory than a double and can hold better accuracy for very small amounts. It can be much slower than a double, so don’t use a float when a double will do.


/* We look at mixing ints with doubles 
   and the explicit cast
   Specifically the double
   Programmer: Jane Doe
   Date : May 2020
*/
 
#include <iostream>
 
using namespace std;
 
int main(){
   int x=4, y=9;
   float z;
   z = y / x;  // no implicit or explicit cast
   cout << "What is the value of z\n";
   cout << z;
}
// Guess what should the value of z be?


9 / 4 = 2 ? Really? Taliga?


So, what happened here ?

sample c++ code showing explicit cast required to make the math work properly


9 divided by 4 should be 2 1/4 or 2.25 but yet the compiler says the answer here is two. Yep, copy the code, click here, select all and paste this code into place before running it. The answer is 2.0

The problem here is that when the y / x calculation was done, the ints couldn’t handle the floating portion of the calculation so it truncated it then transferred its results to the waiting float, ha ha.


#include <iostream>
 
using namespace std;
 
int main(){
   int x=4, y=9;
   float z;
   z = float(y) / x; // explicit int to float cast
   cout << "What is the value of z\n";
   cout << z;
}
// outputs 2.5 This works


Dividing an int by an int with a remainder

When an int is divided by an int that results in a remainder, the ints happily chop off the remainder before stoically passing the resulting int to the float. Much like a poker player presenting a blatant lie.

That is why float = int / int can sometimes give the wrong answer. So z = 9 / 4 gives 2 when the 9 and 4 are straight faced ints when we know the answer should be 2.25.


The c++ explicit cast

The answer is to cast one of the ints to a float then do the division which should result in a float. Now the poker player unabashedly passes the 2.5 to the smiling z float variable like it should have in the first place. We call this an explicit cast.

z = float(y) / x;


Next Lesson 4 – C++ Char, String Types

Top