編輯:
我添加了一個函數來顯示學生的平均品位爲字母。
using namespace std;
被認爲是不好的做法,有時可能會很危險。檢查this。 聲明SIZE
作爲全局變量也被認爲是不好的做法。
#include <iostream>
#include <string>
void getData(int sizeArray, std::string courseName[], float examOne[], float examTwo[], float examThree[], float average[]);
std::string letterGrade(int grade);
void highestLowestAverageByExam(float tExamArray[], int tSize, float & tHighestGradeExam, float & tLowestGradeExam, float & tAverageGradeExam);
int main()
{
// local declaration
const int SIZE = 5;
std::string courseName[SIZE];
float examOne[SIZE];
float examTwo[SIZE];
float examThree[SIZE];
float average[SIZE];
getData(SIZE, courseName, examOne, examTwo, examThree, average);
std::cout << "\n\n\n";
for (int i = 0; i <SIZE; i++)
{
std::cout << courseName[i] << " " << examOne[i] << " " << examTwo[i] << " "
<< examThree[i] << " " << average[i] << " " << letterGrade(average[i]) << std::endl;
}
std::cout << "\n";
float highestGradeExam = 0;
float lowestGradeExam = 0;
float averageGradeExam = 0;
highestLowestAverageByExam(examOne, SIZE, highestGradeExam, lowestGradeExam, averageGradeExam);
std::cout << "Exam number 1: Highest grade = " << highestGradeExam
<< " Lowest grade = " << lowestGradeExam
<< " Average grade = " << averageGradeExam << std::endl;
return 0;
}
void getData(int sizeArray, std::string courseName[], float examOne[], float examTwo[], float examThree[], float average[])
{
for (int i = 0; i < sizeArray; i++)
{
int count = 0;
std::cout << "Enter Course Name: ";
std::cin >> courseName[i];
std::cout << "enter First Exam Grade: ";
std::cin >> examOne[i];
count++;
std::cout << "enter Second Exam Grade: ";
std::cin >> examTwo[i];
count++;
std::cout << "enter Third Exam Grade: ";
std::cin >> examThree[i];
count++;
average[i] = (examOne[i] + examTwo[i] + examThree[i])/count;
}
}
std::string letterGrade(int averageGrade)
{
if (averageGrade >= 0 && averageGrade <= 100)
{
const int NUMBER_CATEGORIES = 11;
const std::string GRADE_LETTER[] = { "F", "D", "D+", "C-", "C", "C+", "B-", "B", "B+", "A-", "A" };
const int LOWEST_GRADE_SCORE[] = { 0, 60, 67, 70, 73, 77, 80, 83, 87, 90, 93 };
int category = 0;
while (category < NUMBER_CATEGORIES && LOWEST_GRADE_SCORE[category] <= averageGrade)
{
category++;
}
return GRADE_LETTER[category - 1];
}
else
{
return "Average grade is not valid.";
}
}
void highestLowestAverageByExam(float tExamArray[], int tSize, float & tHighestGradeExam, float & tLowestGradeExam, float & tAverageGradeExam)
{
tHighestGradeExam = tExamArray[0];
tLowestGradeExam = tExamArray[0];
for (int i = 1; i < tSize; i++)
{
if (tExamArray[i] > tHighestGradeExam)
{
tHighestGradeExam = tExamArray[i];
}
if (tExamArray[i] < tLowestGradeExam)
{
tLowestGradeExam = tExamArray[i];
}
}
tAverageGradeExam = (tHighestGradeExam + tLowestGradeExam)/2;
}
爲什麼不直接使用存儲數據的數組,然後創建一個sum變量,然後除以數組的大小?在這種情況下,它會是3 – 2016-12-01 01:38:52
數組不計算。代碼確實。數組存儲數據。你不能創建一個計算平均值的數組,因爲數組不能算數。 –
這是真的,謝謝 – red