与for循环中的变量混淆

时间:2020-06-26 16:01:22

标签: c++ for-loop variables

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循环中使用的位置,在哪里从中获取其值以便以后可以对其进行操作。有什么类比可以使这一点更容易理解吗?

3 个答案:

答案 0 :(得分:0)

我难以理解变量total在哪里使用 这个for循环,从中获取其价值,以便以后进行 操纵它。是否有一些类比可以使此操作更容易 明白吗?

int total{};
//       ^^

大括号将变量total初始化为0

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

答案 1 :(得分:0)

在函数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 :(得分:0)

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

Similary,int count{ 1 };中的初始化程序等效于int count(1);;或int count = 1;

相关问题