简体   繁体   English

是否可以在 c++ 的 do while 循环中创建 while 循环?

[英]Is it possible to create a while loop within a do while loop in c++?

int main() 
{
    int num;
    char continue_ = 'N';

    do 
    {
        cin>>num;
        
        while(num <=10 && num >= 1)
        {   
            int new_num = factorial(num);
            cout<<new_num;
        }

        cin>> continue_;
            
    }
    while(continue_ == 'y' || continue_ == 'Y' );
    
    return 0;
}

I have a factorial function created already that works.我已经创建了一个可以工作的阶乘 function。 My professor wants us to have a while loop within the do-while, that verifies that the num is a min of 1 and a max of 10. However, when I run it infinitely continues printing the answer as a while loop should.我的教授希望我们在 do-while 中有一个 while 循环,以验证 num 的最小值为 1,最大值为 10。但是,当我无限运行它时,会继续打印答案,就像 while 循环一样。 I tried applying a break after the print.我尝试在打印后休息一下。 However, it stops the program all together can anyone help?但是,它会一起停止程序,有人可以帮忙吗?

If the input 'num' is between 1-10, then program enters to the second while loop and prints new_num.如果输入 'num' 在 1-10 之间,则程序进入第二个 while 循环并打印 new_num。 But the 'num' variable value is not updated inside of the second while loop.但是“num”变量值不会在第二个 while 循环内更新。 Therefore the condition of the second while loop is always true.因此,第二个 while 循环的条件始终为真。 As a result of this, the program will infinitely print 'new_num'.因此,程序将无限打印“new_num”。 If you want to verify whether the 'num' is between 0-10 then use a 'if' condition instead of 'while' loop.如果要验证“num”是否在 0-10 之间,请使用“if”条件而不是“while”循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM