2013-02-25 149 views
0

我想知道如果有人能給我一個這個快速的幫助。我剛完成了我的辣椒課程。它計算素數的素數和平均數。但是,當我看到自己的答案和老師的回答時,我似乎在任何一個方向都偏離了0.5。辣椒計算差異

她:

在第50個chiliads總質數:每千年5133 平均數量:102.66

我:

在第50個chiliads總質數:5134 平均數per chiliad:102

我有點確定這是因爲我的回答不是正確舍入,但我試過showpoint setprecison,它沒有工作:(你們有沒有任何suggestio NS?我感謝任何幫助!謝謝!這是我的代碼。

#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; 

} 

回答

1
primeCount (0, 50000); 

long primeCount (long x, long y) 
{ 
... 
    for (b = x; b <= y; b++) 

基本上,你是一個素數計數0。

+0

感謝您的提示!我相應地調整了它,現在它完美地工作:) – Jason 2013-02-25 07:52:54

+0

我最終做的是在第16行,我將0改爲1,因爲0不是素數。然後,我加了(雙)到第70行。最後,我讓b = 1。那就是訣竅。感謝您的提示!我留下了設置精度,因爲它確實讓我的列看起來更整齊:) – Jason 2013-02-25 08:00:52