[英]How do I return the values of the Student Function to Main so that I can I use them for the Display Function?
程序:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
//Structure
struct Student{
string name;
int pMark;
int eMark;
double avg;
string result;
};
//Functions
Student info(int arrSize, Student arrStudent[10]);
void display(int arrSize, Student arrStudents[10]);
//Main program
int main() {
Student arrStudents[10];
int arrSize;
cout << "How many Students are there(max 10): ";
cin >> arrSize;
info(arrSize, arrStudents);
display(arrSize, arrStudents);
return 0;
}
//Student Function
Student info(int arrSize, Student arrStudent[10]){
int counter = 0;
while(counter < arrSize){
cout << "\nStudent " << (counter + 1) << " info:";
cout << "\nEnter the name: ";
cin >> arrStudent[counter].name;
cout << "Enter the participation mark: ";
cin >> arrStudent[counter].pMark;
cout << "Enter the exam mark: ";
cin >> arrStudent[counter].eMark;
arrStudent[counter].avg = (arrStudent[counter].pMark + arrStudent[counter].eMark) / 2.00;
if (arrStudent[counter].avg >= 50) {
arrStudent[counter].result = "Pass";
}
else {
arrStudent[counter].result = "Fail";
}
counter++;
}
return arrStudent;//(Return Array)?
}
//Display Function
void display(int arrSize, Student arrStudents[10]) {
cout << endl << "Name\t\t Average\t\t Result" << endl;
for (int counter = 0; counter < arrSize; counter++) {
cout << arrStudents[counter].name << "\t\t"
<< fixed << setprecision(2)
<< arrStudents[counter].avg << "\t\t\t"
<< arrStudents[counter].result << endl;
}
}
我尝试使用 function 这样,但我不确定它是否正确?
//Student Function
Student info(int arrSize, Student arrStudent[10]){
int counter = 0;
while (counter < arrSize) {
cout << "\nStudent " << (counter + 1) << " info:";
cout << "\nEnter the name: ";
cin >> arrStudent[counter].name;
cout << "Enter the participation mark: ";
cin >> arrStudent[counter].pMark;
cout << "Enter the exam mark: ";
cin >> arrStudent[counter].eMark;
arrStudent[counter].avg = (arrStudent[counter].pMark + arrStudent[counter].eMark) / 2.00;
if (arrStudent[counter].avg >= 50) {
arrStudent[counter].result = "Pass";
}
else {
arrStudent[counter].result = "Fail";
}
counter++;
}
return arrStudent[arrSize];
}
我是编码新手(在大学里),所以我们仍然需要了解向量、指针和引用。 这就是为什么我没有尝试任何其他方法。 如果可以通过避免这些方法来解决它,我将非常感谢这些解决方案。
您正在按值传递数组的值,您应该通过引用传递它们,因此您应该使用指针,
示例 function:
Student info(int arrSize, int *arrStudent)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.