I have 2 questions:
1. How do I make it so that if a certain file isn't entered, it wont proceed?
2. My numbers wont show the decimal points and I'm not understanding why, I used setprecision
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
ifstream inFile;
ofstream outFile;
string file;
int Bailey ,
Harrison,
Grant,
Peterson,
Hsu,
Bowles,
Anderson,
Nguyen,
Sharp,
Jones,
McMillan,
Gabriel;
int m, f , cc, un;
cout << " Welcome to Maggie's Student Survey!"; //Introduction
cout << endl;
cout << " Enter the file name you wish to open: " <<endl;// promts the user to enter the file name they want to open
getline(cin, file);
inFile.open(file);
outFile.open(file);
cout << " The Student's Genders, Colleges, and Scores:" << endl;
cout << "\n Bailey M CC 68"
"\n Harrison F CC 71"
"\n Grant M UN 75"
"\n Peterson F UN 69"
"\n Hsu M UN 79"
"\n Bowles M CC 75"
"\n Anderson F UN 64"
"\n Nguyen F CC 68"
"\n Sharp F CC 75"
"\n Jones M UN 75"
"\n McMillan F UN 80"
"\n Gabriel F UN 62 " << endl; //the data file so the user can see what they opened
m = (75 + 79 + 75 + 75) / 4; // average will be 76
f = (71 + 69 + 64 + 68 + 75 + 80 + 62) / 7; //average will be 69.85
cc = (71 + 75 + 68 + 75) / 4; //average will be 72.25
un = (75 + 69 + 79 + 64 + 75 + 80 + 62) / 7; // average will be 72
cout << " Total Males Average Scores: " << std::setprecision(2) << m << endl;
cout << " Total Females Average Scores: " << std::setprecision(2) << f << endl;
cout << " Total Community College Average Scores " << std::setprecision(2) << cc << endl;
cout << " Total University Average Scores: " << std::setprecision(2) << un << endl;
system("pause");
答案 0 :(得分:1)
关于你的第二个问题,我提出了一个解决方案,首先你需要声明m,f,cc,un为双打,而不是整数。 然后尝试将其他数字存储为其他变量。例如对于cc:
#include <iostream>
#include <iomanip>
int main()
{
double a, b, c, d; // or ints, here it doesn't matter
a = 71;
b = 75;
c = 68;
d = 75;
double cc = (a + b + c + d) / 4; //average will be 72.25
std::cout << " Total Community College Average Scores " << std::setprecision(4) << cc << '\n';
system("pause");
}
如果你这样做,精度可以工作。我将其设置为4以显示您的号码,2是不够的。
其他解决方案(可能更容易):
#include <iostream>
#include <iomanip>
int main()
{
double p;
p = 71 + 75 + 68 + 75;
double cc = p / 4; //average will be 72.25
std::cout << " Total Community College Average Scores " << std::setprecision(4) << cc << '\n';
system("pause");
}
答案 1 :(得分:1)
falco的答案解决了您需要如何将平均变量更改为doubles
。另外,我将除以4.0
而不是4
,以使浮点除法更明确。否则,您最终可能会执行整数除法并获得预期结果。
如果文件不存在,以下示例应该让您开始使程序不继续。我假设你的意思是“如果没有输入某个文件”。
std::cout << "Enter the file name you wish to open: " << std::endl;
std::getline( std::cin, filename );
std::ifstream inFile( filename, std::ios::in );
if ( !inFile )
{
// return if the file couldn't be opened
return 1;
}
// write some stuff to the file