程序中的第一个星号是如何被打印出来的

How does the first star in this program get printed?

本文关键字:打印 第一个 程序      更新时间:2023-10-16

我想弄清楚这个程序中的第一个星星是如何被打印出来的。当控制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,然后是金字塔的第一颗星