Hi, I forgot how to do the decimal precision aka magic formula
Like after you run the program it give you 4 decimal places but i only want 2 decimal places

Hope someone can help!!

Thank You!!

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;

void cal_avg(ifstream& input, ofstream& output);

int main()
{
	ifstream input;
	string inf;
	ofstream output;
	string outf;

	cout << "Please enter the input file name that you want to open: " << endl;
	cin >> inf;
	cout << "Please enter the output file name that you want to open: " << endl;
	cin >> outf;

	input.open(inf.c_str());
	output.open(outf.c_str());

	if(input.fail() && output.fail())
	{
		cout << "The input file " << inf << "and the output file" << outf << "could not be opened!" << endl;
		exit(1);
	}

	cal_avg(input, output);

	input.close();
	output.close();

	return 0;
}

void cal_avg(ifstream& input, ofstream& output)
{
	double val, sum=0, avg=0;
	int i=0;

	while(input >> val)
	{
		sum += val;
		i++;
	}
		avg = sum / i;
		cout << "The average is: " << avg << endl;
		output << "The average is: " << avg << endl;
}

Two options:

1) You can output 2 decimal places
2) You can change the actual precision of variable to 2 decimal places

For option number 1, here is an example : float f = 1.23456f; cout.precision(3); cout << f; and for option number 2, here is an example :

float a = 1.2345;
float b = int(a*100) / 100.0f; 
cout << b;

Hi
So for option 1: Do I another variable to define avg in line 48?

//would it be something like this?
double new_avg;
avg = sum / i;
float new_avg = avg; cout.percision(2); cout << "The average is: " << new_avg << endl;
//When i use float, Do i need to declare it before using it?

Here's a decent iomanip tutorial:

http://www.cprogramming.com/tutorial/iomanip.html

If you scroll about halfway down, you'll see an example. For some reason they have the entire webpage as a link so I can't copy and paste the code. Look for "Setting the precision of numerical output with setprecision".

There are some examples on this page:

http://www.fredosaurus.com/notes-cpp/io/omanipulators.html

You can also use printf instead.

http://www.devdaily.com/blog/post/software-dev/cheat-sheet-reference-printf-format-specifier-syntax/

It's a matter of personal preference, though I imagine that since you're using C++, stick with iomanip.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.