【问题标题】:What is this for loop doing C++ ? tempList[j+1]这是什么 for 循环做 C++ ?临时列表[j+1]
【发布时间】:2018-03-12 00:27:34
【问题描述】:

我知道输出并且打印正确:49 49 46 40 31 19 4 但是它是如何通过这个等式 tempList[j+1] + j * num 到达那里的?据我了解,如果我拿走+ j * num,结果将是1010101。但是在括号中添加j+1 使其成为444444。那么j*num 是如何成为最终结果的呢?

#include <iostream>

using namespace std;

int main()
{
    int *tempList;
    int num = 3; 

    tempList = new int[7];
    tempList[6] = 4;

    for (int j = 5; j >= 0; j--)
    {
        tempList[j] = tempList[j+1] + j * num; 
    }

    for (int j = 0; j < 7; j++)
    {
        cout << tempList [j] << " ";
    }

    cout << endl;
 } 

【问题讨论】:

  • 那么j*num 是如何成为最终结果的呢? -- 因为程序完全按照它的指示去做?
  • 是的,但我的问题是它是如何到达那里的?这个等式让我很困惑: tempList[j+1] + j * num
  • 为什么不手动跟踪它,或者更好的是,使用调试器跟踪它?该程序没有魔法。
  • 我试过,甚至把它拆开,如上所述。能给我举个例子吗
  • 拿出一张纸。用方框绘制tempList 数组。有一列 j 值。逐步运行该循环,擦除并替换生成的值的框,并递减j 值。如果你做不到,那么我不知道还能告诉你什么,因为它是编程的基础——能够手动完成。

标签: c++ arrays loops for-loop


【解决方案1】:

没有什么奇怪的。

num=3
tempList[6]=4

j=5, num=3
tempList[5] = tempList[6]+ j*num
tempList[5]=4 + (5*3) = 19

j=4, num=3
tempList[4] = tempList[5]+ j*num
tempList[4]=19 + (4*3) = 31

j=3, num=3
tempList[3] = tempList[4]+ j*num
tempList[3]=31 + (3*3) = 40

j=2, num=3
tempList[2] = tempList[3]+ j*num
tempList[2]=40 + (2*3) = 46 

j=1, num=3
tempList[1] = tempList[2]+ j*num
tempList[1]=46 + (1*3) = 49

j=0, num=3
tempList[0] = tempList[1]+ j*num
tempList[0]=49 + (0*3) = 49

【讨论】:

    猜你喜欢
    • 2018-08-12
    • 2023-01-13
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 2019-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多