【问题标题】:Why should I declare variable in the While loop为什么要在 While 循环中声明变量
【发布时间】:2021-02-17 06:40:43
【问题描述】:
#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”时,它在每行中只打印一个星号,要在每一行中打印另一个星号,我必须在第一时间声明它循环体,为什么会这样?

【问题讨论】:

  • 提示:在您刚刚引用的两种情况下,stars 的值是什么之前遇到以下循环条件:while (stars &lt;= line_number)?仅供参考,您没有必须在第一个while循环中声明它。您可以通过在前面提到的最内层循环开始之前立即重置stars = 1; 来获得相同的行为。这本身可能是对正在发生的事情的更大暗示。
  • @BassemWanies ,如果您对我的回答感到满意,请标记它。或者如果有任何混淆,请告诉我。

标签: c++ variables while-loop declaration


【解决方案1】:

您使用的变量“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

【讨论】:

    【解决方案2】:

    您不必重新声明变量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;
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-02
      • 1970-01-01
      • 2011-12-23
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 2015-03-25
      • 2017-07-20
      相关资源
      最近更新 更多