创建空心正方形c++
creating hollow square c++
我已经写了这段代码,但不知怎么的,当它要求用户输入一个新数字来创建一个正方形时,它不会打印正方形。有人能给我解释一下吗?
// ask user to repeat the process again at end of the first promt
while ( num > 1 || num < 20 )
{
ask user to repeat the process again at end of the first promt
while ( num > 1 || num < 20 )
{
// ask user t enter a square
cout << "Please enter size of square between #1-20: n";
cin >> buf; num = atoi (buf.c_str());
cin.ignore(1000, 10);
// process of printing square
while ( num >= a)
{
b = 1;
while ( num >= b )
{
if ( a == 1 || a == num || b == 1 || b == num )
cout << "*";
else
cout << " ";
b++;
}
cout << endl;
a++;
}
我没有看到将a
初始化为1的代码,所以它可能有一些任意值。如果该任意值大于num
,则外部循环将永远不会启动。
值得一提的是,在这种情况下,我将使用for
循环,因为您事先知道限制是什么,类似于以下伪代码:
# Top line
for i = 1 to num (inclusive):
output "*"
output newline
# Middle lines
for i = 2 to num-1:
output "*" # Left char
for j = 2 to num-1: # Middle chars
output " "
output "*" and newline # Right char
# Bottom line
for i = 1 to num (inclusive):
output "*"
output newline
这样就不必担心循环体中的条件检查了。
一个很好的经验法则是,对于已知的迭代开始前计数使用for
,对于预先不知道迭代频率的循环使用while
。
另一个可能的问题是你的状况:
while ( num > 1 || num < 20 )
不管num
的值是多少,这总是正确的,因为您使用的是逻辑或||
。思考各种可能性:
num <= 1 : false or true -> true
num == 2..19 : true or true -> true
num >= 20 : true or false -> true
如果你想在值在1..20范围之外的情况下继续循环,你应该使用:
while ( num < 1 || num > 20 )
然后你会得到以下结果:
num < 1 : true or false -> true
num == 1..20 : false or false -> false
num > 20 : false or true -> true
你的代码还有很多其他潜在的问题,也就是说:
- 你似乎有两次外环在里面
- 您似乎没有定义
b
或num
- 您似乎没有在外循环(检查它)之前设置
num
- 我怀疑您的意思是在
cin.ignore()
调用后立即关闭while ( num > 1 || num < 20 )
循环,因为它意味着继续进行,直到您得到一个从1到20的值,然后绘制正方形。目前,即使您输入99,也将绘制一个正方形
可能不是最好的代码,但它可以在六行中完成。给。
for (int y = o; y < height; ++ y) {
for (int x = 0; x < width; ++x) {
cout << (y == 0 || y == (height - 1) || x == 0 || x == (width - 1) ? '*' : ' ' );
}
cout << endl;
}
相关文章:
- 试试完美的正方形,你能给点小费吗
- OpenGL绘制三角形而不是正方形
- 在 OpenGL 中旋转一个正方形
- (C++) 解密自定义的波利比乌斯正方形
- 使用变异模板的正方形总和
- 我无法完全理解这段代码来检查一个完美的正方形
- 编写一个函数,用递归函数检查数字是否是正方形
- QScriptEngine评估数字C 的正方形或立方体
- 无法获取索引缓冲区以在 OpenGL 中绘制正方形
- 图形面积(等分三角形、正方形、五角形、六边形、七重奏、八进制)使用 if-else (C++)
- 如何在 cpp 中绘制带有图案的填充正方形
- 打印最大非完美正方形
- 我的任务是在框架内打印一个字符串,例如一个正方形
- 渲染正方形时的 OpenGL 黑屏
- 检查4分是否为正方形
- 计算填充国际象棋64正方形所需的米饭总数
- 简单的C 嵌套以用于循环程序,以打印带有星星错误的正方形
- 找出一个正方形逻辑中可能的网格数量,但代码不接受超过六个输入,它停止并说.exe停止工作
- 算法以准确检测正方形和圆之间的重叠
- OPENCV:为击中创建一个正方形结构元素