程序中的第一个星号是如何被打印出来的
How does the first star in this program get printed?
我想弄清楚这个程序中的第一个星星是如何被打印出来的。当控制stars的循环第一次遇到时,stars的值应该是1,因为在循环中进行了初始化,light的值应该是0,因为在light的声明中它被赋值为0。打印第一个星号的条件是(stars <Light),意思是(1><哦,那是错的,对吗?但是程序还是打印出了一个星星!发生什么事了?>
#include <iostream>
using namespace std;
int main()
{
int empty = 10; // stars intial value
int light = 0; // space inital value
int lines; // number of lines on screen
int stars; // number of stars each iteration
int spaces; // number of spaces each iteration
for(lines = 0; lines <= 10; lines++) // number of lines
{
for(spaces = empty; spaces > 0; spaces--) // number of spaces
{
cout << " ";
}
for(stars = 1; stars < light; stars++) // number of stars
{
cout << "*";
}
cout << endl;
light += 2;
empty--;
}
}
第二次循环时:
for(lines = 0; lines <= 10; lines++) // number of lines
light
变量将为2,因为循环中的这一行将light
的当前值加2:
light += 2;
第二次循环时打印星号。
关键是:灯光+= 2;
我想你认为它是第一次打印它,但它不是。
在第二次迭代时打印。
当light = 2时,打印1颗星
在主外for循环的第二次迭代中,light的值将为2
,因为它在第一次主外for循环迭代结束时增加了…因此,由于stars
每次进入它自己的内部for循环时被初始化为1
的值,因此它将小于2
,因此您将能够打印出星号字符。同样,在每个连续的循环周期中,stars
在该点的值将小于light
,并将继续打印星形字符。
第一次循环运行时,它不会打印任何星星,而是将light的值增加2。到第二次迭代时,你会得到星星<轻,你将有你的第一颗星星打印>
玩
运行时重新检查输出-当我运行上面的代码时,我得到一个初始的std::cout,然后是金字塔的第一颗星
相关文章:
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- std::find,返回所有找到的值的替代方法,而不仅仅是存在重复的向量的第一个值
- 如何仅读取文本文件中的第一个值
- 如何打印下一个字母直到 Z 并继续到 A?
- 在C++中,如何在第一个"system()"结束后执行第二个"system()"?
- c++:如何打印出一个强制转换的 int 值?
- 为什么在C++中增加指针后打印了一个值而不是 NULL/0?
- 查找不在标准中的第一个值::设置<int>最小-最大值
- C++:忽略第一个 cin.ignore 之后的输入
- 在C++中打印多个矢量的第一个值
- C++去除前x个元素的有效方法,在不改变向量大小的情况下将第x+1个元素推到第一个
- C++第一个cout将不会打印
- 我们可以在第一个else-if条件结束后使用另一个else-if条件吗
- 如何使用 Boost C++ 打印第 n 个字符串拆分?
- OpenGL:第二个VBO破坏了第一个VBO
- C++ 链表程序打印最后一个数据项 n 次
- 为什么第一个Dynamic_cast没有投射到基类?
- 虽然第三次循环循环,尽管在我眼中没有满足它的条件,因此打印了一个空字符串
- 传递给函数后的 GDB 打印数组仅打印第一个值,但数组仍然完好无损
- 代码是打印相同的值时,它应该随机生成每一次,而且它不打印数组中的第一个值