C++ 环路故障
我希望运行char,以确定交换机是否运行。我在为循环设置起点时遇到问题。 我正在使用integers选项和size创建一个模式。该选项选择模式类型1-4,大小决定模式将具有的列数和行数C++ 环路故障,c++,C++,我希望运行char,以确定交换机是否运行。我在为循环设置起点时遇到问题。 我正在使用integers选项和size创建一个模式。该选项选择模式类型1-4,大小决定模式将具有的列数和行数 #include <iostream> using namespace std; int main() { int option, size; char run; cout << "This program is writen by Alex Walter. " <<
#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' );
}
#包括
使用名称空间std;
int main()
{
int选项,大小;
焦炉;
cout您试图使用run
用于两个不同的目的:
输入“y”或“y”继续运行,或输入“n”或“n”停止运行
计算循环的数量,并在switch语句中使用以确定正在运行的运行
解决方案是使用两个单独的变量。使用上面的#2的run
,然后需要对其进行初始化,这意味着在程序的最顶端给它一个初始值。要初始化,请在声明它的位置提供值,如下所示:
int run = 1;
注意,我将类型从char
更改为int
——因为在switch语句中,您将它与整数而不是字符进行比较
现在请确保<代码>运行< /COD>每个循环都增加(添加1)。(您也应该考虑如果/<代码>运行/代码>达到5,而不是在Switter语句中),
在switch语句之后这样做
现在添加一个额外的变量,例如input
,并使用它,而不是使用cin
获取输入的底部的run
,并将其与while
语句中的“y”或“y”进行比较。您也可以在顶部声明变量,不需要初始化它,尽管这样做是一个好习惯无论如何都要进入初始化状态:
char input = 'Y';
你在哪里初始化run
到任何东西?你得到了未定义的行为,因为run
从来没有初始化过。我想你想要你的开关
语句使用选项
那些cout
是lovely@Kunal你在开玩笑吗?@CharlesSalvia如果我的switch语句使用option来确定模式那么我该如何再次循环运行呢?同意@CharlesSalvia。此外,因为run是一个字符,所以你应该有类似于case“1”或“a”之类的情况。另一个礼貌的建议是,不要复制和粘贴你的整个代码,因为它们可能有一些不相关的东西,试着只发布你有问题的部分代码。让生活变得更美好对于正在调查此事的其他人,sier:)
char input = 'Y';