为什么要在 While 循环中声明变量

Why should I declare variable in the While loop

#include <iostream>
using namespace std;
int main()
{
    int n, line_number = 1, stars = 1;
    cout << "Enter lines number " << endl;
    cin >> n;
    while (line_number <= n)
    {

        while (stars <= line_number) {

            cout << "*";
            stars++;
        }
        line_number++;
        cout << endl;
    }

}

我刚开始学编程 在这段代码中绘制一个直角三角形,当我用其余变量声明变量“stars”时,它在每行中只打印一颗星,要在每一行中打印另一个星,我必须在第一个 while 中声明它循环体,为什么会这样?

您使用的变量 'stars' 的递增速度与变量 'line_number' 相同。例如,在第 1 行,值为 1 的 'stars' 等于值为 1 的 'line_number',因此第 1 行仅打印一个“*”,这是正确的。然而,从第 2 行开始,由于 'star' 在第二个 while 循环中递增 1,而 'line_number' 在第一个 while 循环中递增 1,因此两个变量将分别与值 3,3 一起递增, 4,4 分别依此类推,因此第 2 行的第二个 while 循环会将 (stars<=line_number) 与 (2<=2) 进行比较,因此它只会循环一次。要解决这个问题你只需要在第一个while循环中将'stars'值重置为1,第二个while循环从1循环到行数。

您不必重新声明变量 stars。只需为其分配值 1。因为对于每一行,您都必须打印 as many ' * ' as the linenumber itself,就是这样。

#include <iostream>
using namespace std;
int main()
{
    int n, line_number = 1, stars = 1;
    cout << "Enter lines number " << endl;
    cin >> n;
    while (line_number <= n)
    {

        while (stars <= line_number) {

            cout << "*";
            stars++;
        }
        line_number++;
        stars = 1;
        cout << endl;
    }

}