簡體   English   中英

素數函數C ++

[英]Prime number function C++

我正在使用文件流,將整數讀入infile,然后將那些正數讀入指向outfile的數組。 我對數組進行冒泡排序,並且需要找到平均值,方差,標准差和素數。 我的質數函數遇到問題,它根本沒有將任何內容流式傳輸到我的文件中。 我的終端在這里的照片 這也誤算了我的平均值。 我已經進行了排序並獲得了數據功能,因此它看起來並不混亂。

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <cmath>
using namespace std;
const int MAX = 30;
void getVariance(int[], int);
bool isPrime(int[], int);
double average(int[], int);
int main()
{
  string inputfilename, outputfilename;
  ifstream infile;
  ofstream outfile;
  int prime, n, sum =0, posnumbers[MAX], countp=0, countn=0\
;
  double variance, stdv, avg=0;


  cout << "Please enter the name of the input file: ";
  cin >> inputfilename;
  infile.open(inputfilename.c_str());
  cout << "Please enter the name of the output file: ";
  cin >> outputfilename;

       ///////////////////////postive ////////////////////////////                            

  outfile.open(outputfilename.c_str());
  if(!infile)
    cout << "file not open for input" << endl;
  else
    {
     prime = isPrime(posnumbers, n);
     outfile << "=======================" << endl << endl;
     outfile << "Positive #'s in the File" << endl;
     for (int i=0; i<n; i++)
         {
           if (posnumbers[i]>=0)
             {
               countp++;
               sum = sum + posnumbers[i];
               outfile << posnumbers[i] << endl;
               if (posnumbers[i] == prime)
                 outfile << posnumbers[i] << endl;
             }
         } 



     outfile << "average " <<  sum/n << endl;
     outfile << "variance " << variance << endl;


///////////////////////// functions/////////////////////                                 



bool isPrime(int posnum[], int n)
 {
   for (int i=2; i<=posnum[n]/2; i++)
     if (posnum[n] % i ==0)
       return false;
     else
       return true;
 }

double average(int posnum[], int n)
{
  double sum = 0.0;
  for (int i=0; i<n; i++)
    {
      sum += posnum[n];
    }
  return sum / n;
}
bool isPrime(int posnum[], int n)
 {
   for (int i=2; i<=posnum[n]/2; i++)
     if (posnum[n] % i ==0)
       return false;
     else
       return true;
 }

這是行不通的。 原因是當數字不可分割時,您立即返回true。 例如,如果posnum[n]為3,那么您的模檢查將失敗,並且您將立即返回true,而不檢查所有其他可能除數的數字。

此外, isPrime當前僅檢查一個數字的素數,但這未反映在調用代碼中。

prime = isPrime(posnumbers, n);

由於isPrime返回bool ,因此prime現在為0或1。

if (posnumbers[i] == prime)
    outfile << posnumbers[i] << endl;

這意味着該行將僅輸出所有為0或1的數字,具體取決於質數的值。 你應該叫isPrime為每一個元素posnumbers代替,如果它返回true打印。

對於isPrime ,請嘗試以下操作:

bool isPrime(int posnum[], int n) {
    for (int i = 2; i <= posnum[n] / 2; ++i) {
        if (posnum[n] % i == 0) {
            return false;
        }
    }
    return true;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM