我想知道是否有人可以给我一个快速帮助。我刚刚完成了我的辣椒计划。它计算质数和素数的平均数。然而,当我看到我的答案和老师的答案时,我似乎在任何一个方向都像.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;
}
答案 0 :(得分:1)
primeCount (0, 50000);
long primeCount (long x, long y)
{
...
for (b = x; b <= y; b++)
基本上,您将0视为素数。