C++ 功能显示问题
我的任务是编写一个程序,根据用户输入的数据显示星号(*)字段。我让代码正常工作,但我的导师要求将它们至少放在两个函数中。displaybanner功能不起作用。getData运行并要求用户输入值,但输入后程序停止。出了什么问题C++ 功能显示问题,c++,C++,我的任务是编写一个程序,根据用户输入的数据显示星号(*)字段。我让代码正常工作,但我的导师要求将它们至少放在两个函数中。displaybanner功能不起作用。getData运行并要求用户输入值,但输入后程序停止。出了什么问题 #include <iostream> using namespace std; void displaybanner(int numrows=0, int numcolums=0, int numfields=0); void getData(int
#include <iostream>
using namespace std;
void displaybanner(int numrows=0, int numcolums=0, int numfields=0);
void getData(int numrows=0, int numcolumns=0, int numfields=0);
const char c = '*';
int main(void)
{
getData();
displaybanner();
}
void getData(int numrows,int numcolumns,int numfields)
{
cout << "Welcome to the banner creation program!" << endl;
cout << "Enter the number of rows (1 - 5) --> ";
cin >> numrows;
if(numrows<1 || numrows>5){
cout << "Your entered value is outside the range!" << endl;
cout << "Program will now halt..." << endl;
exit(0);}
cout << "Enter the number of columns (5 - 50) --> ";
cin >> numcolumns;
if(numcolumns<5 || numcolumns>50){
cout << "Your entered value is outside the range!" << endl;
cout << "Program will now halt..." << endl;
exit(0);
}
cout << "Enter the number of rows (3 - 10) --> ";
cin >> numfields;
if(numfields<3 || numrows>10){
cout << "Your entered value is outside the range!" << endl;
cout << "Program will now halt..." << endl;
exit(0);
}
}
void displaybanner(int numfields, int numrows, int numcolumns)
{
for (int i = 0; i < numfields; i++) {
for (int j = 0; j < numrows; j++) {
for (int k = 0; k < numcolumns; k++) {
cout << c;
}
cout << endl;
}
cout << endl << endl << endl;
}
}
#包括
使用名称空间std;
void displaybanner(int numrows=0,int numcolums=0,int numfields=0);
void getData(int numrows=0,int numcolumns=0,int numfields=0);
常量字符c='*';
内部主(空)
{
getData();
displaybanner();
}
void getData(int numrows、int numcolumns、int numfields)
{
库特努姆罗斯;
如果(numrows5){
cout这不起作用,因为您只是在修改函数中的临时/本地值。若要解决此问题,您必须通过引用(使用指针或引用)传递参数
最简单的方法可能是使用引用,例如更改
void getData(int numfields, int numrows, int numcolumns)
到
这将确保保留您对这些参数所做的所有更改,即使在返回调用函数时也是如此。请注意,您不能使用默认参数,但您只需在希望通过参数返回值的位置使用默认参数
然后,您的主要功能应该如下所示:
int main(void)
{
int fields, rows, cols;
getData(fields, rows, cols);
displaybanner(fields, rows, cols);
}
displaybanner
的默认参数均为零:
void displaybanner(int numrows = 0, int numcolums = 0, int numfields = 0);
由于在主模块中调用此函数时没有任何参数,循环的顺序将不会执行(因为索引变量为0,其限制为0)。若要使其正常工作,请将参数传递给displaybanner
,或使其默认参数大于0。思考函数的参数的含义。特别是,如果您不给getData()
,它将打印0颗星,即无。
void displaybanner(int numrows = 0, int numcolums = 0, int numfields = 0);