【发布时间】:2018-02-17 05:39:54
【问题描述】:
所以这个程序将打印完美的数字,但其中一个,2096128,由于某种原因正在打印?非常感谢一些帮助弄清楚发生了什么!谢谢!我不明白为什么一个不完美的数字会在序列中找到它!
#include <iostream>
#include <string>
#include <math.h>
#include <iomanip>
bool isPerfect(int n);
using namespace std;
int main() {
long long perfect = 0;
int first = 0;
first = (pow(2, 2 - 1))*(pow(2, 2) - 1);
cout << first << endl;
for (int i = 3, j = 1; j < 5; i += 2) {
if (isPerfect(i)) {
perfect = (pow(2, i - 1)*(pow(2, i) - 1));
cout << perfect << endl;
j++;
}
}
// pause and exit
getchar();
getchar();
return 0;
}
bool isPerfect(int n)
{
if (n < 2) {
return false;
}
else if (n == 2) {
return true;
}
else if (n % 2 == 0) {
return false;
}
else {
bool prime = true;
for (int i = 3; i < n; i += 2) {
if (n%i == 0) {
prime = false;
break;
}
}
return prime;
}
}
【问题讨论】:
-
欢迎来到 Stack Overflow!听起来您可能需要学习如何使用debugger 来单步执行您的代码。使用好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏差在哪里。如果您要进行任何编程,这是必不可少的工具。进一步阅读:How to debug small programs.
-
pow用于浮点数。对于整数 2 的幂,它只是(1 << x) -
isPerfect()不返回数字是否完美,它返回数字是否为素数。你在哪里检查完美数字? -
您的代码基于不正确的数学。只要
pow(2, i - 1)是质数,pow(2, i - 1)*(pow(2, i) - 1)就是一个完美数。但是你不是在检查pow(2, i - 1)是否是素数,你只是在检查i是否是素数。见en.wikipedia.org/wiki/Perfect_number#Even_perfect_numbers
标签: c++ perfect-numbers