[英]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.