rounding to one decimal place

i'm trying to get the percentage difference to be rounded to 1 decimal place, however this code is not working and is making the output all wrong and mixed up. does anyone know how i could make only the percentage difference rounded to one decimal place? thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
	x=0;
	for (x>=0; x<=100; x++)
	{
		approx = (x*2)+30;
		actual = (x*9.5)+32;
		diff = approx-actual;
		pdiff = (((approx-actual)/approx)*100);


		cout << x << "\t" << approx << "\t" << actual << "\t" << diff << "\t" << "\t"  << std::fixed << std::setprecision(1) << pdiff; ;
		
																						  
	}

	getch();
	return(0);
Did you #include <iomanip>? You need that for setprecision().

I just added in << endl to start a new line for each set of data and it's rounding to one decimal place. You can pull the cout << std::fixed << std::setprecision(1); out to before the other cout statement to get all the numbers in that format.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <iomanip>
using namespace std;

int main() 
{
	
double approx, actual, diff, pdiff;

for (int x=0; x<=100; x++)
	{
		approx = (x*2)+30;
		actual = (x*9.5)+32;
		diff = approx-actual;
		pdiff = (((approx-actual)/approx)*100);
		cout << std::fixed << std::setprecision(1);
		cout << x << "\t" << approx << "\t" << actual << "\t" << diff << "\t" << "\t" << pdiff << endl; 
	}

	return(0);
}


0	30.0	32.0	-2.0		-6.7
1	32.0	41.5	-9.5		-29.7
2	34.0	51.0	-17.0		-50.0
3	36.0	60.5	-24.5		-68.1
4	38.0	70.0	-32.0		-84.2
5	40.0	79.5	-39.5		-98.8
Last edited on
Topic archived. No new replies allowed.