0

When i use float or double in c++ after eight digit is getting overflow, how fix it?

This is my code :

#include <iostream.h> 
#include <conio.h> 
void main() { 
  double x; 
  cout<<"double : "; 
  cin>>x; 
  cout<<endl<<x; 
  getch(); 
}

When cin = 123456789 , this is my cout : 123457e.08.

3
  • 6
    can you show some example code? Commented Jan 21, 2011 at 10:51
  • #include <iostream.h> #include <conio.h> void main() { double x; cout<<"double : "; cin>>x; cout<<endl<<x; getch(); } Commented Jan 23, 2011 at 6:22
  • when cin 123456789 , this is my cout : 123457e.08 Commented Jan 23, 2011 at 6:23

2 Answers 2

5

Use dot: double x = 2398479238749234.0

Sign up to request clarification or add additional context in comments.

1 Comment

Just to elaborate on BarsMonster's answer: by omitting the decimal point, you are actually using integer literals, whose maximum value is INT_MAX (typically 2147483647). If you specify a larger number, it will overflow. Only after this will the value be implicitly cast to a double.
2

If you declare a float you can type f at the end like this:

float var = 123456789.0f;

A simple yet interesting demonstration:

To see the importance of f try this code:

 float f1 = 1.3f;
 //test f1
 if ( f1 == 1.3f )
  std::cout<<"f1 is equal to 1.3f"<<std::endl;
 else
  std::cout<<"f1 is not equal to 1.3f"<<std::endl;

 float f2 = 1.3;
 //test f2
 if ( f2 == 1.3 )
  std::cout<<"f2 is equal to 1.3"<<std::endl;
 else
  std::cout<<"f2 is not equal to 1.3"<<std::endl;

Output:

f1 is equal to 1.3f
f2 is not equal to 1.3

See demonstration at ideone : http://www.ideone.com/QvzEp

1 Comment

If you omit f meaning would not change )

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.