使用嵌套For循环绘制点
Plotting points using Nested For Loops
我对c++比较陌生,我们被分配了这个任务:
编写一个c++程序,要求用户输入1到10之间的数字n。然后程序应该打印出n行。每一个都应该包含与当前行号相同数量的星号。例如:
Please enter a number: 5 * ** *** **** *****
我遇到的问题是,当我使用我写的代码时,它显示错误。
我现在的代码是这样的:
#include<iostream>
using namespace std;
int main() {
int n;
cout << "Please enter a number between 1 and 10:" << endl;
cin >> n;
for (int x = 0; x <= n; x++)
{
for (int y = 0; y <= n; y++) {
cout << "*" ;
}
cout << "*" << endl;
cin.get();
}
return 0;
}
用笔和纸一步一步地完成你的程序逻辑。
对于你的"水平"循环,你每次都要一直到n
。对吗?我想你的意思是只到x
,因为这是每一行增加的值。
另一个问题是你有太多的东西,因为你使用<=
而不是<
。
解决方案就像"@Lightness Races in Orbit"刚刚向你解释的那样。让我补充一下,如果需求只是打印您显示给我们的内容,那么不需要最后一个'*'和'cin.get()':
for (int x = 0; x <= n; ++x)
{
for (int y = 0; y < x; ++y) {
cout << "*" ;
}
// No need for all the rest just print 'new line'
std::cout << "n";
}
现场试试!
不需要嵌套循环。这个程序使用一个for循环也可以工作。
#include <iostream>
using namespace std;
int main()
{
int n = 0;
cout << "Enter a number and press ENTER: ";
cin >> n;
for (int i = n; i < 11; ++i) {
cout << i << " " << endl;
}
return 0;
}
相关文章:
- 如何循环打印顶点结构
- 如何在C++中从两个单独的for循环中添加两个数组
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 正在尝试了解输入验证循环
- OPENCV C .在for循环中在不同的图像像素上绘制一个圆圈(应在每个循环运行时将图像打开)
- fworldperscreenwidththpixel如何用于循环绘制
- 如何在循环中绘制东西(fltk/c )
- 在 openGL 中播放音频而不冻结绘制循环
- 对于循环重复绘制问题
- 在绘制循环中绘制精灵
- 使用 for 循环绘制边框
- 如何为带有循环的 c++ 绘制矩形
- 对于循环奇怪的循环,用于使用 Qt 创建器绘制矩形
- 使用 for 循环 Qt c++ 绘制圆圈
- Q对话框未在循环中绘制
- 是否可以在仅用于循环的形状中绘制形状?如果是,请给我指一个正确的方向
- 在循环中以特定坐标绘制
- 使用嵌套For循环绘制点
- 在主循环之外绘制背景时闪烁
- 在while (window.isOpen())循环之外绘制对象