# difference between float and double

This tip submitted by ankit panwar on 2012-03-10 01:14:36. It has been viewed 47553 times.
Rating of 5.4 with 247 votes

In c++ any value like 4.12 is treated as a double by default.

Comparing floats and doubles can be a tricky business because of the difference in precision leading to minute errors. For example:

```float a = 4.12;

if(a==4.12)
{
cout<<"hello";
}
else
{
cout<<"bye "<

This will show you the output as "bye 4.12"

Why?

Because by default 4.12 is a double (such as in the if statement or in the assignment to our variable), but storing it in a float it loses some precision, and so comparing then comparing a double with a float lead to microscopic changes in the precision of the number--remember that floats and doubles are not precise.

Two lessons here: one is that floating point numbers shouldn't be compared directly most of the time, and the other is that the default size and type of a hard-coded floating point number is double.

For more on floating point numbers, read understanding floating point numbers--accuracy and precision.

10
9
8
7
6
5
4321

More tips

function abTest(element_name_sets) {
var element_to_show;
var element_count = element_name_sets.length;
var i;
for ( i = 0; i < element_count; i++ )
{
if ( Math.random() <= 1 / ( element_count - i ) ) {
break;
}
}
var element_name_set = element_name_sets[ i ];
for ( i = 0; i < element_name_set.length; i++ )
{
element_to_show = document.getElementById( element_name_set[ i ] );
element_to_show.style.display = "block";
}
}

Popular pages

Exactly how to get started with C++ (or C) today
C Tutorial
C++ Tutorial
5 ways you can learn to program faster
The 5 Most Common Problems New Programmers Face
How to set up a compiler
8 Common programming Mistakes
What is C++11?
How to make a game in 48 hours

How to create a shared library on Linux with GCC - December 30, 2011
Enum classes and nullptr in C++11 - November 27, 2011
Learn about The Hash Table - November 20, 2011
Rvalue References and Move Semantics in C++11 - November 13, 2011
C and C++ for Java Programmers - November 5, 2011
A Gentle Introduction to C++ IO Streams - October 10, 2011

Custom Search

<!--
//-->