为什么我会得到一个无限循环(因子)?

问题描述 投票:0回答:2

正整数n的正确除数是除了n本身以外均匀划分n的所有正整数。例如,16的适当除数是1,2,4和8。

丰富的数字是大于0的整数,使得其适当的除数之和大于整数。例如,12是丰富的,因为1 + 2 + 3 + 4 + 6 = 16,其大于12。

缺陷数是大于0的整数,使得其适当的除数之和小于整数。例如,8是不足的,因为1 + 2 + 4 = 7小于8。

完美数字是大于0的整数,因此其适当除数的总和等于整数。例如,6是完美的,因为1 + 2 + 3 = 6。

enter image description here

#include <iostream>
#include <cctype>
#include <iomanip>
#include <cmath>
using namespace std;

    int main()
    {
      int current;
      int possible;
      int sum=0;
      int facts=0;

      cin >> current;

目前是:17 -5 246

      while(cin){
        cout << current;
        for (possible=1; possible<= current; possible++)
          {
            if(current%possible==0)
              {
              sum= sum + possible;
              facts++;
             if(sum-current > current)
              cout << "is abundant and has" << facts  << "factors" << endl;
            if(sum-current < current)
              cout << "is deficient" << endl;
            if(current < 2)
              cout << "is not abundant, deficient or perfect" << endl;
            if(current == sum-current)
              cout << "is perfect" << endl;

          }
        }
      }

        return 0;
      }

这就是我应该得到的:17缺乏-5不丰富,缺乏或完美。 246是丰富的,有8个因素,而我得到一个无限循环

c++ for-loop if-statement while-loop
2个回答
1
投票

问题是你使用cin作为while循环的条件,因为循环将继续执行,直到没有更多的数据要读取。

请参阅What's the difference between while(cin) and while(cin >> num)

而是在循环中输入当前数字,即

while(cin >> current){
    /* Your code */
}

注意:

要在Linux终端中停止读取用户的输入,请输入Ctrl + D.

而且我也看到你的逻辑不对,所以你可能会得到错误的结果,而你必须自己解决。


0
投票

您可以使用int current [3]而不是int current并检查当前数组的接收结束而不是while(cin)

© www.soinside.com 2019 - 2024. All rights reserved.