我是 C++ 的初学者,在尝试创建函数来执行每个任务时遇到了很多麻烦。我想我可以在主函数中处理每个任务,但我不知道如何将它们分解为单独的函数(例如:我不知道如何打破 .txt 文件的读取并将其显示为单独的函数。)
此外,对于“分数”,我不断收到一条错误消息,上面写着“下标需要数组或指针类型”,但我不知道这是什么意思。
注意:我还没有完全完成程序,所以曲线、显示曲线和平均曲线还没有制作函数,我稍后会做。
//this program reads data from a .txt file, displays the scores, finds the average score, finds the highest score, and displays the curve
#include <iostream>
#include <fstream>
using namespace std;
//function prototypes
void readscores (int); // read exam scores into an array from examscores.txt
void displayscores (int); // display scores in row of four scores
double average (const double scores [], int); //??? calculate average score and display
double maxscore (const double[], int); // find max and display
double curve (const double []); //find the "curve" based on the highest scores
double displaycurve (const double []);// display curves in rows of four
double averagecurve (const double []); //calculate the average curved score and display
int main ()
{
const int array_size = 30; //array size
double scores[array_size];//array of 30 elements
int count = 0;
ifstream inputfile;
//open file
inputfile.open("ExamScores.txt");
//read scores
while (count < array_size && inputfile >> scores[count])
count ++;
//display scores
cout << "The numbers are:";
for (count = 0; count < array_size; count++)
displayscores(scores[count]);
//calculate the average
cout << "The average is:";
average (scores, array_size);
//find the max score and display
cout << "The maximum score is:";
maxscore (scores, array_size);
return 0;
}
void displayscores (int num)
{
cout << num << " ";
}
double average (const double scores, int array_size)
{double total = 0;
double average;
for (int count = 0; count < array_size; count ++)
total += scores[count];
average = total /array_size;
}
double maxscore (const double scores, int array_size)
{double max;
max = scores [0];
for (int count = 1; count < array_size; count++)
{if (scores[count] > max)
max = scores[count];
}
return max;
}
这些是 .txt 文件中的数字或分数:
67 64 83 81 72 75 85 81 56 88 71 80 90 58 78 74 84 64 72 69 78 87 84 72 83 68 62 88 70 75
如果我的编码完全错误,我深表歉意,因为教授不喜欢解释他在教什么,而且这个学期已经完成了一半,所以我仍在努力围绕基本概念进行思考。