【问题标题】:confused with a variable within a for loop与 for 循环中的变量混淆
【发布时间】:2020-06-26 16:01:22
【问题描述】:
int getTo(int value)
{
    int total{};

    for (int count{ 1 }; count <= value; ++count)
        total += count;
    return total;

}

int main()
{
    getTo(5);
    return 0;
}

第一次发帖,如有格式问题,请见谅。

我很难理解变量 total 在这个 for 循环中的使用位置,它从哪里获取它的值以便以后能够对其进行操作。是否有一些类比可以使这更容易理解?

【问题讨论】:

  • getTo 函数所做的是将 int 作为其函数参数,main 提供数字 5。然后返回值 5 + 4 + 3 + 2 + 1 = 15。跨度>
  • 如果您想为您的问题添加信息,请不要在 cmets 部分进行,因为它很容易被忽略。你可以随时edit你的问题;)
  • 程序员的秘密武器是调试器。使用调试器,您可以以人脑可以处理的速度运行此代码,并实时观察程序的状态、变量和变化。例如,您可以单步执行程序,一次执行每一行(或指令,如果您需要详细了解发生了什么)。调试器是可用的最好的程序员生产力工具之一,您越早习惯使用它们,就越早获得好处。
  • 感谢您快速而有帮助的回复,我没想到会这样!在阅读了 cmets 并使用调试器逐步完成之后,正如有人建议的那样,它变得更加明显。谢谢。

标签: c++ for-loop variables


【解决方案1】:

在函数getTo()中,total首先被默认初始化(意味着它的值是0)。

for-loop 设置一个变量count = 1,然后不断增加它直到达到value,每次迭代都将它添加到total。对于getTo(5),它会这样做:

  1. getTo(5)total 初始化为 0

  2. getTo(5)count 初始化为 1

    count = 1,所以将1 添加到total,--> total = 1 现在增加count

    count = 2, 所以将2 添加到total, --> total = 3 现在增加count

    count = 3,所以将3 添加到total,--> total = 6 现在增加count

    count = 4, 所以将4 添加到total, --> total = 10 现在增加count

    count = 5, 所以将5 添加到total, --> total = 15 现在增加count

  3. getTo(5) 返回total,等于15

【讨论】:

    【解决方案2】:

    我很难理解变量 total 的使用位置 这个 for 循环,它从中获取它的价值,以便以后能够 操纵它。是否有一些类比可以使这更容易 明白吗?

    int total{};
    //       ^^
    

    花括号默认将变量total初始化为0

    然后该函数将 1 到 5 的值相加并将其存储在 total 中。

    【讨论】:

      【解决方案3】:

      int total{}; 声明中的空初始化器将变量初始化为零,就像 int total(0);int total = 0; 一样

      类似,int count{ 1 }; 中的初始化器等价于int count(1);;或int count = 1;

      【讨论】:

        猜你喜欢
        • 2015-09-12
        • 2011-05-27
        • 1970-01-01
        • 1970-01-01
        • 2016-11-24
        • 2021-03-11
        • 2016-06-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多