search

Home  >  Q&A  >  body text

C++的循环问题

在一个for循环体中,我需要用到两个变量。比如说:

for(int n=0;int f=n+1&&f<5;++n)
    cout<<f;

就像这种形式。我在vs2015上一跑就死循环了(。-_-。) 那这种情况下我应该如何改写代码让它能成功运行呢?
谢谢。

黄舟黄舟2804 days ago584

reply all(6)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-17 13:45:07

    First look at your code

    for(int n=0;int f=n+1&&f<5;++n)
        cout<<f;
        

    The intermediate loop termination condition is int f=n+1&&f<5, && has a higher priority, so it is equivalent to int f=(n+1&&f<5). Obviously, f is always 1. If you know the reason, you can see how to change it. You got it.

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 13:45:07

    在for 循环定义两个变量
    for  (   int  a, b ;   ;  )
    
    你的测试条件,没看懂

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 13:45:07

    for(int n=0f=0;f<5;++n) 
    
    cout<<f;
    f=n+1;
    

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 13:45:07

        for (int n = 0; ; ++n){
            int f = n + 1;
            if (f >= 5) break;
            cout << f;
        }

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 13:45:07

    for (int n = 0, f = 0; (f = n + 1) && (f<5); ++n)
        cout << f;

    reply
    0
  • 黄舟

    黄舟2017-04-17 13:45:07

    Thank you for your generous advice, I have found the answer. The reason is that I put an assignment statement where the conditional judgment is.
    The Android client will not fix the problem, so I would like to thank you all here

    reply
    0
  • Cancelreply