我正在尝试将数据输入到数组,然后使用函数打印它们,但我不确定如何组织代码。
#include <iostream>
using namespace std;
void showGrade(double grade[], int size);
int main()
{
double grade[];
int size;
for (int i = 0; i < size; i++)
{
cout << "Please enter the number of grade" << endl;
cin >> size;
}
showGrade(grade, size);
return 0;
}
void showGrade(double grade[], int size) //How many grade we have
{
for (int counter = 0; counter < size; counter++)
{
cout << "Please enter your grades: " << endl;
cin >> grade[counter];
cout << "Here are your grades: " << endl;
}
}
我希望看到我输入了多少个成绩
,然后显示它们。
2019 年 8 月 28 日更新
我想出了如何在 main 函数中成功地做到这一点。但我真正想要的是将它们放在一个单独的函数中。我的新代码在函数调用时有错误,类型名称是不允许的,需要一个 ')'。我如何让它发挥作用?
#include <iostream>
using namespace std;
void showGrades(double ar[], int size);
int main()
{
double ar[20];
int size;
showGrades(double ar[size], int size);
system("pause");
return 0;
}
void showGrades(double ar[], int size) {
cout << "Please enter the number of grade "; // array size
cin >> size;
cout << "Please enter your grades " << endl;
for (int i = 0; i < size; i++) {
cin >> ar[i];
}
cout << "The grades you entered are: " << endl;
for (int i = 0; i < size; i++) {
cout << ar[i] << endl;
}
}
最佳答案
首先,你需要使用标准容器 <强>
std::vector
而不是double grade[];
,因为你想要一个可变长度的 根据用户输入排列。其次,您在
中使用了未初始化的size
变量for (int i = 0; i < size; i++)
因此它将使用垃圾值进行初始化。你不需要
for-loop
一个好的开始是:
#include <iostream>
#include <vector> // std::vector
void showGrade(std::vector<double>& grade)
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -> pass the vector by ref, as the grades should be inseted to the it
{
// the logic
}
int main()
{
int size;
std::cout << "Please enter the number of grade" << endl;
std::cin >> size;
std::vector<double> grade;
grade.reserve(size); // reserve memory for unwanted re-allocations
showGrade(grade);
return 0;
}
在阅读了更多有关 std::vector
的内容后,我将其留给您完成。
此外,不要使用 using namespace std;
进行练习。阅读更多:
Why is "using namespace std;" considered bad practice?
关于c++ - 如何将数据输入数组并通过函数打印出来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57615663/