Question about percision

I know that you can set the precision in the cout statement but can you set it for the cin statement. the reason i ask this is i am comparing the fraction part of a double in several if statements but as i step through the program it skips all conditons. i added a watch and it seems the number is just above what i am checking for. i am only doing something if the frac part is .3 or above and this is just a test program to see if it works
example:
have the fraction part when computed using modf is .300003
i am trying to see if the frac part = .3 but when run the if statement is ignored.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <iomanip>
#include <math.h>

using namespace std;

int main()
{
  int i;
  double total,num,fracpt,intpt;
  total=0.0;
  num=0.0;
  for(i=0;i<6;i++)
  {
    cout<<i<<"\n";
	cout<<"Enter a number in format num.num ";
	cin>>num;
	cout<<"\n";
	total=total+num;
	cout<<fixed<<setprecision(1)<<total<<"\n";
    fracpt=modf(total,&intpt);
	cout<<fracpt<<"\n";
	if (fracpt == .3)
	{
	  fracpt = .0;
      total=intpt+1+fracpt;
	}
	else
      if (fracpt == .4)
	  {
        fracpt=.1;
        total=intpt+1+fracpt;
	  }
	  else
        if (fracpt == .5)
		{
          fracpt=.0;
		  total=intpt+1+fracpt;
		}
		cout<<total<<"\n";
  }
return 0;
}

thank you for any help you can give me.
Referring to the code you posted above, replace lines 23-40 with this:

1
2
3
4
5
6
7
    switch ((int)((fracpt + 0.05) * 10)) {
    case 3: fracpt = .0; break;
    case 4: fracpt = .1; break;
    case 5: fracpt = .0; break;
    }
    total=intpt+1+fracpt;
    cout<<total<<"\n";

The idea is that it multiplies the floating point number by 10, pushing the first decimal into the one's position, then converts it to an int, chopping off any remaining decimals. Then it switches on that single digit. Remove the +0.05 if you don't want to round it.
Topic archived. No new replies allowed.