Trouble using setprecision and while loop.

I'm using setprecision inside the while loop and I just want it to be used on that same statement and not throughout the whole code but I'm not sure how. In case I wasn't so clear with my description, I think you will understand what I'm trying to say if you look at the output below.

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
int main()
{
double R;
double I;
int c;
double V;
int count=0;
		
cout << "How many circuits do you have? ";
cin >> c;

		while (count < c)
		{
			cout << "Circuit 1 Data .. "<<endl;
			cout << "R (kiloohms) = ";
			cin >> R ;
			cout << "\n";
			cout << "V (Volts) = ";
			cin >> V;
			cout << "\n";
		
			I = V/R ;
				
cout << "Without using 'setprecision function' \nI (miliampere) = " <<I <<endl;
cout << "With using 'setprecision function' \nI (miliampere) = " <<setprecision (2) <<I <<endl;
						
			count++;
		}
return 0;

}
	
	


[output]

Circuit Data ..
R (kiloohms) = 3.5

V (Volts) = 9

Without using 'setprecision function'
I (miliampere) = 2.57143
With using 'setprecision function'
I (miliampere) = 2.6

Circuit Data ..
R (kiloohms) = 8

V (Volts) = 1.5

Without using 'setprecision function'
I (miliampere) = 0.19
With using 'setprecision function'
I (miliampere) = 0.19

Thank you for using Circuits Calculator.
Press any key to continue
Last edited on
You can use the function precision():

http://www.cplusplus.com/reference/ios/ios_base/precision/

It returns the previous setting. So you can reset it after you're done.
I got the same result.
Topic archived. No new replies allowed.