float to int blunder can any one explain this

here is a simple program :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include<iostream>
using namespace std;
int main()
{
int n;
double z;
cin>> z;
cout <<z <<"...."<< (1/z);


cout <<"\n";
n =1/z;
cout<<"n is "<<n<<"\n";
n=1/.1;
cout<<"n is "<<n<<"\n";

}


INPUT = .1 ;

OUTPUT : 0.1....10
n is 9
n is 10

if I am not wrong .1 is stored in temporary memory as a double constant , so whats the difference between the two statements , why is output different in the two cases... Plzz Help...
There shouldn't be anything wrong with your code.. I don't see any reason for the outputs to be different.
Neither does my computer. my output looks like this:
0.1....10
n is 10
n is 10
which compiler did you use ? I use g++ on ubuntu ..
Last edited on
Ah, i'm using Visual Studio 2008.

Though I'm getting the proper output, my compiler does give me a warning: "Conversion from int to double, possible loss of data" or something.
Maybe that has more of an effect with G++ than it does Visual Studio?
Try making 'n' a double.
See this: http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.18


Note the actual error is likely very small, but it's exaggerated by the cast to int.
Last edited on
Topic archived. No new replies allowed.