循环问题
Trouble with a loop
我想要我的字符运行,以确定我的开关是否会运行。我在放置循环的开头时遇到问题。我正在使用整数选项和大小创建模式。该选项选择模式类型 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' );
}
我只编写了足够的代码来为示例创建模式。但我也在寻找一种方法来循环模式的创建。请不要只是给我一个答案,我真的在试图解决这个问题,我只是被困住了,与班上的任何学生都没有联系。
您正在尝试将run
用于两个单独的目的:
- 输入"y"或
- "Y"继续运行,或输入"n"或"N"停止运行。
- 计算循环数并在 switch 语句中使用来确定您正在执行的运行。
解决方案是使用两个单独的变量。 对上面的 #2 使用run
,但随后您需要对其进行初始化,这意味着在程序的最顶部给它一个初始值。 若要初始化,请提供声明它的值,如下所示:
int run = 1;
请注意,我将类型从 char
更改为 int
- 因为在 switch 语句的情况下,您将其与整数而不是字符进行比较。
现在确保每个循环都递增(向其添加 1 run
。 (您还应该考虑如果/当run
达到 5 时会发生什么,这在您的 switch 语句中没有!
++run;
在某个地方执行此操作,例如在 switch 语句之后。
现在添加一个额外的变量,例如 input
,并使用它而不是在底部run
,在那里您获得cin
输入并将其与 while
语句中的"y"或"Y"进行比较。 您也可以在顶部声明变量,并且不需要初始化它,尽管无论如何都要开始初始化它是一个好习惯:
char input = 'Y';
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 在java中解决这段代码时面临循环中的问题
- 当调用switch语句中的函数时(即使函数不包含循环),似乎是永不结束的循环的问题
- 在 for 循环中查找问题时遇到困难
- 嵌套for循环C++的问题(初学者)
- 退出简单while循环时出现问题
- 循环无限运行C++解决骑士之旅问题
- Visual Studio 2017循环自动向量化问题
- 我试图制作一个程序,要求用户输入问题和答案,但程序循环不正确
- 嵌套While循环不起作用(C++问题)
- 使用 GMP 的 while 循环出现问题
- 遇到此问题时遇到困难:允许用户输入数组的值并使用 for,而循环也输出输入的最大数字
- OpenMP for 循环并行性问题
- 这个返回元素位置的基于循环的函数有什么问题?
- 为什么循环会导致指针出现问题?
- 使用基于范围的循环迭代矢量时出现问题
- 在 c++ 中循环遍历数组时遇到问题
- 运行无限循环的最小二叉树问题
- 在C++中循环访问自定义结构列表的小问题
- 在 for 循环中更新两个变量时遇到问题C++