【问题标题】:Why am I getting an infinite loop (factors)?为什么我得到一个无限循环(因素)?
【发布时间】:2018-03-05 07:00:43
【问题描述】:

正整数 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个因子 相反,我得到了一个无限循环

【问题讨论】:

  • 是时候learn how to debug your programs 并专门学习如何使用调试器了。使用调试器,您可以逐行执行代码并监控变量及其值。
  • 一个提示,rubber duck debugging(也在我之前的链接中讨论过)将帮助您找到(以及逐行浏览您的代码):您何时何地阅读输入?
  • 你知道while(cin) { /*...*/ }是什么意思吗?

标签: c++ for-loop if-statement while-loop


【解决方案1】:

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

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

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

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

注意:

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

而且我也看到您的逻辑不正确,因此您可能会得到错误的结果,而这必须由您自己解决。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-31
      • 1970-01-01
      • 2012-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多