我想知道是否有人可以快速帮助我解决这个问题。我刚刚完成了我的chiliad程序。它计算素数和平均素数。但是,当我查看我的答案和老师的答案时,我似乎在任何一个方向上都偏离了 0.5。
她有:
前 50 个千历的质数总数:5133 每个千历的平均数:102.66
我有:
前 50 个千纪的质数总数:5134 每个千纪的平均数:102
我有点确定这是因为我的答案没有正确四舍五入,但我尝试了 showpoint setprecison 但它没有用:(你们有什么建议吗?感谢任何帮助!谢谢!这是我的代码。
#include <iostream>
#include <cmath>
#include <iomanip>
const int CHILIADS = 50;
bool isPrime (long n);
long primeCount (long x, long y);
using namespace std;
int main()
{
cout << setw(10) << left << "Start" << setw(10) << "End" << setw(24) << "Number of Primes" << endl;
primeCount (0, 50000);
return 0;
}
// Determines whether the number is prime
bool isPrime (long n)
{
int a;
if (n == 1)
{
return false;
}
for (a = 2; a <= (n / 2); a++)
{
if ((n % a) == 0)
{
return false;
}
}
return true;
}
// Counts and organizes the prime numbers using the isPrime function
long primeCount (long x, long y)
{
bool prime;
int b;
int c = 1000;
int counter = 0;
int totalSum = 0;
for (b = x; b <= y; b++)
{
prime = isPrime (b);
if (prime == true)
{
counter++;
}
if (b == c)
{
cout << setw(10) << left << (b - 999) << setw(10) << left << b << setw(12) << counter << endl;
cout << fixed << showpoint << setprecision(2) << endl;
totalSum = totalSum + counter;
counter = 0;
c = c + 1000;
}
}
cout << endl << "Total primes in the first 50 chiliads: " << totalSum << endl;
cout << "Average number per chiliad: " << totalSum / CHILIADS << endl;
}