循环快速澄清

huangapple go评论63阅读模式
英文:

For Loop Quick Clarification

问题

这个循环行为与我的预期不同:如何在这里成功评估2。

  • 我解释了它,即control = 2;外部for循环开始(control减小到1);
  • 打印(control=2)执行;
  • sub_control评估为1;内部for循环退出

在这种情况下,外部for循环根本没有进入,看输出。

英文:

Working through some exercise, and this loop behaviour is not as I expected:

void primeFunc(int &number){
    
    bool prime_check = false;

    for( int control = number; control > 1; --control){

        printf("\tcontrol = %d\n", control);

        for( int sub_control = control-1; sub_control > 1; --sub_control){

            printf("\t\tsub_control = %d\n", sub_control);

            if(control % sub_control == 0){
                prime_check = false;
                break;
            }
            else prime_check = true;
            // printf("\nPrime: div/quo :: %d/%d", control, sub_control);

        }
        if(prime_check == true){
            printf("\n%d", control);
        }
    }
}
// function call
int num = 5;
primeFunc(num); //<- clearly showing how parameter is passed to func argument ->

The output of the snippet above:

5       control = 4
                sub_control = 3
                sub_control = 2
        control = 3
                sub_control = 2

3       control = 2

2

How is 2 evaluating successfully here.

  • I exaplained it as control = 2; the outer for loop starts (control decrements to 1);
  • print(control=2) runs;
  • sub_control evaluates to 1; inner for loop exits

In this case, the outer for loop isnt even entered print(control=2) doesnt execute.

edit:

The question really is understanding how the number 2 evaluates with prime_check = true.

  • the for loop is not entered at all, looking at the output

答案1

得分: 1

以下是翻译好的部分:

这个问题实际上是理解数字2如何在prime_check = true的情况下进行评估。

看输出结果,for循环根本没有进入。

这可能是因为我们从前一个循环执行中的控制==3的情况下开始循环,而prime_check仍然为true。因为subcontrol = 2-1,所以sub_control > 1失败了,我们根本不进入sub_control循环...并执行printf("\n%d", control);

英文:

> The question really is understanding how the number 2 evaluates with prime_check = true.
>
> the for loop is not entered at all, looking at the output

This is likely because we start the loop where control==2 with prime_check as still true from the previous loop execution where control==3.
Because subcontrol = 2-1, and therefore sub_control > 1 fails, we never go into the sub_control loop at all... and execute printf("\n%d", control);.

答案2

得分: -2

-- 在比较之前,将控制减少到“>1”,我会使用control--。

对于你如何减少sub_control,也是一样的。

英文:

--control decrememts control before you compare it to ">1",

I would use control--.

the same goes for how you are decrementing sub_control.

huangapple
  • 本文由 发表于 2023年6月29日 12:02:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76577987.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定