为什么我会得到一个无限循环(因子)?
Why am I getting an infinite loop (factors)?
正整数 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)
相关文章:
- 为什么这个递归函数会创建一个无限循环?
- 如何找出为什么我的程序一直有一个无限循环?
- 为什么我有一个无限循环,我如何以不同的方式做到这一点
- WinUsb_WritePipe进入了一个无限循环
- 为什么我会得到一个无限循环(因子)?
- 为什么我总是得到一个无限循环
- 这是一个无限循环吗?程序提前完成
- 为什么它是一个无限循环?
- 为什么我的程序在输入字符时有一个无限循环
- 为什么这段代码最终会进入一个无限循环,读取std::cin
- 如何使其成为一个无限循环
- Tcl_CreateInterp怎么会变成一个无限循环呢
- C++,得到一个无限循环
- C++ 使用 cin.fail(), cin.clear() ---我有一个无限循环,不知道为什么
- 这个递归函数(回文)变成了一个无限循环
- 当对象被卡在一个无限循环中而被破坏时会发生什么
- 代码在小输入时运行良好,但在大输入时就像一个无限循环
- 从文件中读取信息后,会发生一个无限循环
- 数独求解矩阵,而语句给出了一个无限循环
- 为什么这是c++中的一个无限循环