【发布时间】:2017-11-06 00:19:10
【问题描述】:
我的问题在于代码末尾的 if/else if 语句。
if 语句应该在输入 Y 时无限循环,尽管它只运行两次并且不会要求用户在第二次运行时再次运行它
如果用户输入 N,else if 语句应该完全关闭程序
else 语句应不断提示用户输入字符,直到输入有效字符。
-
#include <iostream>
using namespace std;
bool getData(int & width, int & height);
bool isDataValid(int & width, int & height);
void printBox(int & width, int & height);
int main()
{
int width = 0;
int height = 0;
bool validData = false;
getData(width, height);
isDataValid(width, height);
printBox(width, height);
while (validData == false)
{
validData = getData(width, height);
}
system("pause");
return 0;
}
bool getData(int & width, int & height)
{
bool validData = true;
cout << "This program will draw a rectangular box in stars." << endl << endl << "The size of the box will be determined by the width and height" << endl << "that you specify. " << endl << endl << "Enter integer values, because the width represents the " << endl << "numbe of columns, and the hieght represents the number of rows." << endl << endl << "The width should not exceed 79, because 80 is the " << "maximum screen " << endl << "width. Both width and height must be " << "at least 1. " << endl << endl;
cout << "Please enter a width: ";
cin >> width;
cout << "Please enter a height: ";
cin >> height;
cout << endl << endl;
return validData = isDataValid(width, height);
}
bool isDataValid(int & width, int & height)
{
if (width > 0 && width < 80 && height > 0)
{
return true;
}
else
{
cout << "Incorrect entry.\n\n";
return false;
}
}
void printBox(int & width, int & height)
{
const int ROWS = height;
const int COLS = width;
for (int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLS; j++)
{
cout << '*';
}
cout << endl;
}
char choice;
cout << endl << endl;
cout << "Do it again? (Y/N)" << endl;
cin >> choice;
while (toupper(choice == 'Y'))
{
// repeat the program
}
if (toupper(choice == 'N'))
{
cout << "Goodbye.\n\n";
// close program
}
}
【问题讨论】:
-
toupper(choice == 'Y')您将toupper应用于比较的布尔结果,而不是应用于choice值的字符。这没什么意义。我认为是no-op,条件相当于if (choice == 'Y') -
"if 语句应该无限循环" If 语句不循环。循环语句循环。
printBox中没有任何依赖于用户输入的内容。 -
所以会是一个while循环?
-
应该是某种形式的循环。我们将其作为练习留给读者选择。
-
我将
if语句更改为while循环,将else if语句更改为if语句并删除了else语句,因为它对于赋值和只是我试图挑战自己,但这被证明是一个足够的挑战。不确定要包含哪些代码来重复程序或关闭程序而不返回。
标签: c++