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

Why am I getting an infinite loop (factors)?

本文关键字:一个 无限循环 因子 为什么      更新时间:2023-10-16

正整数 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。

在此处输入图像描述

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

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

参考 while(cin) 和 while(cin>> num) 有什么区别

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

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

注意:

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

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

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