如何在c++中获得沙漏模式
How to get an Hourglass pattern in c++
我一直在试图得到这个沙漏模式,一段时间以来,我一直被困在如何进行,它要求用户输入#'s的数量在顶行,并指出行数。如果#的个数小于3,则打印一条错误消息。如果行数少于1,或者少于2个"#",则无效。
无论如何,如果我输入7作为第一行,3作为行数,我一直得到这个模式。
7 # s在顶部
5 #'s
3 #'s
3 #'s
5 #'s
我不需要有3 #的行但我似乎无法摆脱它
下面是我的代码: // Declare and initialize variables
int topRow(0);
int row(0);
int i(0);
int k(0);
int j(0);
// Repeatedly prompt for top row size until valid value is entered
cout << "Enter size of the top row: " ;
cin >> topRow;
while(topRow < 3)
{
cout << "Size of the top tow must be at least three." << endl;
cout << "Enter size of the top row again: ";
cin >> topRow;
}
// Repeatedly prompt for the number of rows until valid value is entered
cout << "Enter number of rows: ";
cin >> row;
while(row == 0 || topRow/row < 2.0 || row < 1.0 )
{
cout << "Invalid number of rows." << endl;
cout << "Enter number of top row again: ";
cin >> row;
}
// Print the hour glass
cout << endl;
for (i=1; i < topRow ; i++)
{
if (i <= row )
{ for (j=1; j <= i-1; j++)
{
cout << " ";
}
for (k=1; k <= topRow - (i*2 - 2) ; k++)
{
cout << "#";
}
cout << endl;
}
else
{
for (j = row ; j >= i - (row - 1); j--)
{
cout << " ";
}
for (k = row ; k >= topRow - (i*2 - 2); k--)
{
cout <<"#";
}
cout << endl;
}
}
// end program
return 0;
您可以在沙漏的后半部分的第一次迭代中添加检查。如果
虽然很乱,那就像这样:
static bool first = true;
if (first) {
first = false;
} else {
// ... second print code
}
7和3的输入现在是:
#######
#####
###
#####
#######
如果你期望其他输入被正确格式化,你有一个更大的问题。
我建议你修改一下你的算法。
相关文章:
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 为什么在保护模式下继承升级不起作用
- 如何在全屏模式下(在OpenGL中)使背景透明
- 为什么使用__LINE_的代码在发布模式下在MSVC下编译,而不是在调试模式下
- 派生类是否可以在抽象工厂设计模式中具有数据成员
- 此模式的C++RegEx
- avrogencpp能为模式中的每种类型生成单独的头文件吗
- 使用可变模板的Broadcaster/Listener模式
- c++方法参数只能在linux的发布模式下自行更改
- 资源管理设计模式
- 使用 mod_gsoap 部署服务时,如何在 Gsoap 中更改 soap 上下文的模式?
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 小字符串优化(调试与发布模式)
- 可视化C++:发布模式的运行时库作为'Multi-threaded Debug DLL'
- 如何设计具有不同类型的通知和观察器的观察者模式?
- 在C++的一系列数字中查找重复模式
- 是否允许使用带有"w+"模式的 freopen 进行标准设置?
- C++ 使用存储在动态数组中的文本文件中的数据查找模式
- С++ wxWidgets:代码架构,设计原则和模式
- 如何在c++中获得沙漏模式