该程序应该使用星号输出不同长度的垂直和水平线。星号的数量和行进方向由用户在输入语句中确定。必须使用switch语句创建它。这是我当前的代码:
int main() {
// Variables
int length = 1;
char direct;
// User input choice
if (length >= 1 && length <= 20) {
cout << "\nEnter the line length and direction: ";
cin >> length >> direct;
}
// If user input incorrect
else {
system("pause");
}
// Switch cases for horizontal or vertical
switch (direct) {
case 'h': for (int count = 0; count <= length; count++) {
cout << "*";
break;
}
case 'H': for (int count = 0; count <= length; count++) {
cout << "*";
break;
}
case 'V': for (int count = 0; count <= length; count++) {
cout << "*" << "\n" << endl;
break;
}
case 'v': for (int count = 0; count <= length; count++) {
cout << "*" << "\n" << endl;
break;
}
default: cout << "Illegal comand" << endl;
}
system("pasue");
}
这是我的水平选择输出语句之一:
Enter the line length and direction: 4 h
***
*
Illegal Command
这是我的垂直选择输出语句之一:
Enter the line length and direction: 4 v
*
Illegal Command
这是我希望水平显示的样子:
Enter the line length and direction: 4 h
****
这是我想要的垂直外观:
Enter the line length and direction: 4 v
*
*
*
*
为什么星号无法正确输出?为什么每次都会输出“非法命令”?还以为我应该注意,我是C ++的初学者。谢谢!
您将break;
陈述放在错误的位置。
case 'h': for (int count = 0; count <= length; count++) {
cout << "*";
break;
}
需要是;
case 'h': for (int count = 0; count <= length; count++) {
cout << "*";
}
break;
请注意,您h
和和具有相同的逻辑H
。您可以将它们结合在一起。
case 'h':
case 'H':
for (int count = 0; count <= length; count++) {
cout << "*";
}
break;
您可以合并案例v
,V
也可以类似。
您仍然可以通过创建辅助功能来编写水平线和垂直线来对其进行改进。
case 'h':
case 'H':
writeHorizontalLine(length);
break;
case 'v':
case 'V':
writeVerticalLine(length);
break;
哪里
void writeHorizontalLine(int length)
{
for (int count = 0; count <= length; count++)
{
cout << "*";
}
cout << endl;
}
void writeHorizontalLine(int length)
{
for (int count = 0; count <= length; count++)
{
cout << "*" << endl;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句