我希望我的char运行,以确定我的开关是否运行。我在循环开始时遇到问题。 我正在使用整数选项和大小创建一个模式。该选项选择模式类型1-4,大小确定模式将具有的列数和行数。
#include <iostream>
using namespace std;
int main()
{
int option, size;
char run;
cout << "This program is writen by Alex Walter. "
<< "The purpose of this program is to create four different patterns of different sizes. "
<< "The size of each pattern is determined by the number of columns or rows. "
<< "For example, a pattern of size 5 has 5 columns and 5 rows. "
<< "Each pattern is made up of character P and a digit, which shows the size. "
<< "The size must be between 2 and 9. ";
cout << "Menu" << endl
<< "1. Pattern One " << endl
<< "2. Pattern Two " << endl
<< "3. Pattern Three " << endl
<< "4. Pattern Four " << endl
<< "0. Quit " << endl;
cout << "Choose an option (between 1 and 4 or 0 to end the program): ";
cin >> option;
cout << "Choose a pattern size (between 2 and 9): ";
cin >> size;
do{
switch(run)
{
case 1:
cout << "Pattern 1: " << endl << endl
<< size << "PPPP" << endl
<< "P" << size << "PPP" << endl
<< "PP" << size << "PP" << endl
<< "PPP" << size << "P" << endl
<< "PPPP" << size << endl;
break;
case 2:
cout << "Pattern 2: " << endl << endl
<< "PPPP" << size << endl
<< "PPP" << size << "P" << endl
<< "PP" << size << "PP" << endl
<< "P" << size << "PPP" << endl
<< size << "PPPP" << endl;
break;
case 3:
cout << "Pattern 3: " << endl << endl
<< "PPPPP" << endl
<< "PPPP" << size << endl
<< "PPP" << size << size << endl
<< "PP" << size << size << size << endl
<< "P" << size << size << size << size << endl;
break;
case 4:
cout << "Pattern 4: " << endl << endl
<< "PPPPP" << endl
<< size << "PPPP" << endl
<< size << size << "PPP" << endl
<< size << size << size << "PP" << endl
<< size << size << size << size << "P" << endl;
break;
}
cout << "Run again?" << endl;
cin >> run;
}while(run == 'y' || run == 'Y' );
}
我只编写了足够的代码来为示例创建模式。 但我也在寻找循环创建模式的方法。请不要只是给我一个答案我真的想弄明白我只是卡住了并且没有接触过我班上的任何学生。
答案 0 :(得分:1)
您尝试将run
用于两个不同的目的:
解决方案是改为使用两个单独的变量。对上面的#2使用run
,但是你需要初始化它,这意味着在程序的最顶端给它一个初始值。要初始化,请提供您声明它的值,如下所示:
int run = 1;
注意我已将类型从char
更改为int
- 因为您在切换语句的情况下将其与整数(而非字符)进行比较。
现在确保run
每次循环递增(加1)。 (你还应该考虑当run
达到5时会发生什么,这不在你的switch语句中!)
++run;
在切换语句之后的某处执行此操作。
现在添加一个额外的变量,例如input
,并在底部使用run
代替cin
输入while
并将其与&#39; y进行比较#39;或者&#39; Y&#39;在char input = 'Y';
声明中。您也可以在顶部声明变量,并且不需要对其进行初始化,尽管无论如何都要习惯初始化它:
{{1}}