简体   繁体   English

虽然循环不会继续

[英]While loop won't continue

int Day = 20;
while (Day >= 1)
{
   cout << Day << " ";
   userNum = Day / 2;
   cin >> Day;
}

I don't get why the loop doesn't work.我不明白为什么循环不起作用。 I want the output to be 20 10 5 2 1我希望输出为20 10 5 2 1

Any help and if possible with explanation.任何帮助,并在可能的情况下提供解释。

I don't understand what the purpose of cin is here, but if you want the output you requested in the question:我不明白cin的目的是什么,但如果你想要你在问题中请求的输出:

// Example program
#include <iostream>
#include <string>

using std::cout;
using std::endl;

int main()
{
 int Day = 20;
  while (Day >= 1)
  {
    cout << Day << " ";
    Day /= 2;
  }
}

You can see you stop whenever Date reaches 1 or is less than 1. And you divide it by 2 repeatedly.你可以看到当Date达到 1 或小于 1 时你就停止了。然后你将它反复除以 2。 First, it becomes 20;首先,它变成 20; then you divide it by 2 and it reaches 10;然后你将它除以 2,它达到 10; then you divide by two again and it reaches 5;然后你再除以 2,结果是 5; then 5/2 is 2.5 but rounds to 2;那么 5/2 是 2.5 但四舍五入到 2; and then 2/2 is 1, and finally exits the program.然后2/2就是1,最后退出程序。

Here it is compiled.编译到这里

Try this尝试这个

int Day = 20;
while (Day >= 1)
{
    cout << Day << " ";
    Day = Day / 2;      
}

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

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