【发布时间】:2019-08-22 19:04:05
【问题描述】:
我正在尝试将数据输入到数组中,然后使用函数打印它们,但我不确定如何组织代码。
#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;
}
}
我希望看到我输入了多少grades,然后显示出来。
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;
}
}
【问题讨论】:
-
double grade[];std::vector。 -
int size; for (int i = 0; i < size; i++) {- 这永远行不通。size未初始化。 -
using namespace std;- 这通常是个坏主意。 -
不相关:我不希望名为
showGrade的函数从成绩中获取输入。我希望它只显示成绩。应该创建一个InputGrades函数来处理输入任务。一般来说,一个函数应该只做一件事(即使那一件事是聚合一堆函数的结果,每个函数都做一件事)并根据它所做的一件事命名。这使您可以构建非常简单且易于测试的函数,作为更复杂程序的构建块,随时测试所有内容。 -
哦,我以为我已经初始化了大小。那么我应该在哪里做呢?在主函数中?
标签: c++ arrays algorithm function user-input