Have you ever needed to represent numbers with extreme precision in C++? Well, this is the article for you! In this tutorial, you will learn all about floats and doubles, which add decimal places onto the ends of integers. Thus, you can be more precise when trying to represent numbers.
If you are a beginner and want to learn to code from scratch, check out our FREE 30-minute introduction course here: training.mammothinteractive.com/p/learn-to-code-in-30-minutes
Let’s take a look at an example. If you feel like following along in real time, go on over to rextester.com. This site allows you to code in the main window, and test out your code instantly.
Start off by declaring an integer with a value of 5:
int i = 5;
In rextester.com, your main coding screen should look like this:
int i = 5;
int main ()
std:cout << "Hello, world!\n";
In order to test our code, replace the
"Hello, world!\n" with
i. Scroll down to the bottom and press “Run It”.
You will see the number “5” appear at the bottom of the screen.
Now let’s see what happens when we try to add a decimal place onto our integer.
int i = 5; to
int i = 5.5; and run the code.
As you can see, the console only prints out the decimal “5”. It ignores the decimal because integers are not designed to recognize the decimal place. This is where floats and doubles come in.
Below your integer, declare a float of the name j and a double of the name k:
float j; double k;
Give the float a value of 5.4, and the double a value of 5.3:
float j = 5.4; double k = 5.3;
This time, we want to output not just i, but j and k as well. To do so, add standards for the j and k. Note: add standard end alls to the end of each of the three lines in order to ensure that you start on a new line.
std:cout << i << std::endl; std:cout << j << std::endl; std:cout << k << std::endl;
As you can see by running the code, the double and the float both represent decimal places. They both recognize that there is one decimal place after the numbers.
Let’s see how many decimal places these two can recognize. As an example, change
If you scroll down and run the code, you can see that the compiler only recognizes the code to 5 decimal places, and it’s the same for both floats and doubles. This is only characteristic of this compiler. In some other compilers, doubles can contain twice the number of decimal places as floats can. However, this is only necessary with extremely large data sets where you need extreme precision.
In everyday coding, the difference is pretty negligible.
Want to learn more? Sign up for our FREE 30-minute introduction course here: training.mammothinteractive.com/p/learn-to-code-in-30-minutes. Happy coding and see you soon!
- Writer of blog posts and books at Mammoth Interactive. Can also be found posting to Mammoth Interactive's social media.