第二个if语句遇到问题只能读取十个值。如果我删除程序将编译。我需要它为我已经尝试过几次修改的作业,所以这里的内容可能无法反映我的最后一次尝试。用if语句编译C ++ homework编译错误。详细说明在发布之前我需要添加多少详细信息,更多详细信息
#include <iostream>
#include <fstream>
using namespace std;
/**********************************************************************
* Get File
* This function will prompt the user for the name of the file and
* return it.
*********************************************************************/
void getFileName(char fileName[])
{
//prompt the user
cout << "Please enter the filename: ";
cin >> filename;
ofstream fout(fileName);
}
/**********************************************************************
* Read
* This function will read the file and return the average score of the
* ten values.
*********************************************************************/
float readFile(char fileName[])
{
cout.setf(ios::fixed); //no scientific notation
cout.precision(0); //no decimals
//In case of error
ifstream fin(filename);
if (fin.fail())
{
cout << "Error reading file \"" << fileName << "\"" << endl;
exit(0);
}
float data; //always need a variable to store the data
float i = 0; //don't forget to initialize the variable
float gradeSum = 0;
float average;
//Add up all the grades
while (fin >> data) //while there was not an error
{
gradeSum += data; //do the work
i++;
}
// Hint: Make sure you only read ten values.
if (i != 10)
{
//tell the user what happened
cout < "Error reading file \"" << fileName << "\"" << endl;
exit(0);
}
//Calculate average grade
average = gradeSum / i;
//Close file
fin.close();
return average;
}
/**********************************************************************
* Display function
* This function will display the average score to zero decimals of
* accuracy.
*********************************************************************/
void display(float average)
{
cout << "Average Grade: " << average << "%" << endl;
}
/**********************************************************************
* main calls average grade and file name
***********************************************************************/
int main()
{
char fileName[256];
getFileName(fileName);
int average = readFile(fileName);
return 0;
}
答案 0 :(得分:2)
注意if语句相对于while循环的位置。你的if语句什么时候运行?你的while循环何时运行?
考虑到这些,你如何调整你的while循环以考虑你的限制(当i = 10时循环停止执行)?
我希望这可以帮助您更好地理解您需要做的事情,而不会破坏太多的答案。
P.S。如果i!= 10,那么if块的内容将在现场退出程序,而不执行任何操作。
if (i != 10)
{
//tell the user what happened
cout < "Error reading file \"" << fileName << "\"" << endl;
exit(0);
}
答案 1 :(得分:1)
关于流操作符的简单错误。
这一行:
cout < "Error reading file \"" << fileName << "\"" << endl;
应该是:
cout << "Error reading file \"" << fileName << "\"" << endl;
此外,您还有其他错别字来阻止您的代码编译:即整个filename
和fileName
的大小写混合使用情况。在我将这些变量namings一致地fileName
修复后,它编译了。
答案 2 :(得分:0)
您的cout
无效。 cout << "Average Grade: " << average << "%" << endl;
代替"cout < Average Grade: " << average << "%" << endl;