我是 C++ 编程的新手,我的一个程序有问题
#include <iostream>
using namespace std;
bool IsPerfect(int n);
int main ()
{
for(int i=1; i<100; i++){
IsPerfect(i);
}
return 0;
}
bool IsPerfect(int n){
int sum;
for(int x=1; x<n; x++){
if(n%x==0){
sum+=x;
return true;
cout <<n;
}
else{
return false;
}
}
}
我正在尝试创建一个将列出完美数字的程序,但我找不到关于为什么它不打印的错误。
最佳答案
我看到 3 个问题:
- 你的算法是错误的。您的循环在数字第一次被任何因子(包括 1)整除时终止。参见 Wikipedia算法的解释。
- 你有一个未初始化的变量
int sum;
此外,您只会写信给它,而不会以有用的方式阅读它。 - 您有无法访问的代码。你的
cout << n;
在循环中永远不会被击中。
尝试以下更正的代码:
#include <iostream>
#include <cassert>
using namespace std;
bool IsPerfect(int n)
{
int sum = 1;
for(int x = 2; x < n; ++x)
{
if(n % x == 0)
sum += x;
}
return sum == n;
}
int main ()
{
for(int i=1; i<100; i++){
if (IsPerfect(i))
cout << i << endl;
}
assert(IsPerfect(6));
assert(IsPerfect(28));
assert(IsPerfect(496));
return 0;
}
关于c++ - 为什么我的程序不打印完美整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17029232/