簡體   English   中英

C ++計算gpa和標准偏差

[英]C++ calculate gpa and standard deviation

我正在嘗試計算txt文件中學生的標准差和平均值。 我的平均成績下降了,但是在使用函數來計算5個等級的標准偏差時遇到了麻煩。 我的原型是無效統計(double,double,double,double,double,double&ave,double&sd); 我被困在這一點上。 我不知道輸出我的標准偏差還是我的虛函數。 謝謝

#include <iostream>
using namespace std;
#include <cmath>
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
float getValue(char);
void stats(double&grade1,double&grade2,double&grade3,double&grade4,double&grade5,double&ave,double&sd);

int main() {

    cout << "Name\t\tAverage\t\tDeviation\n";

    string name;
    int count;
    char grade;
    float ave,sum;
    ifstream input;
    input.open("data.txt");



          input >>name;
          while (name!="XXX") {
          cout<<name<<"\t"<<"\t";
          sum=count=0;
          input>>grade;

          while (grade!= 'X' ){
              sum+=getValue(grade); //sum = sum+grade
              count++;
             input>>grade;

          }
          if (count>0)ave=sum/count;
          else cout<<"no average";
          cout<< setprecision (2)<<fixed <<ave<<"\n";
          input>>name;



          }


return 0;
    }
float getValue(char x){
float ans=0;
        switch(x){
        case 'A': ans=4.0;break;
        case 'B': ans=3.0;break;
        case 'C': ans=2.0;break;
        case 'D': ans=1.0;break;
        }
        return ans;
        }
void stats(double&grade1,double&grade2,double&grade3,double&grade4,double&grade5,double&ave,double&sd)
{

    double var;
    var=(pow((grade1-ave),2)+pow((grade2-ave),2)+pow((grade3-ave),2)+pow((grade4-ave),2)+pow((grade5-ave),2))/5;
    sd=sqrt(var);

}

刪除以#define開頭的行。 它沒有執行您認為的操作,並導致了您的神秘錯誤消息。

首先,對於標准偏差,您使用了錯誤的公式。 看看Wikipedia上的頁面 正確的操作順序是:

  1. 計算成績與平均成績之間的差異
  2. 平方您剛剛計算出的所有差異。

現在,您必須了解這些數字的平均值,因此:

  1. 全部加起來
  2. 將總和除以5(在這種情況下,當然是!)

這是您的差異。 最后,

  1. 取方差的平方根。

現在您有了標准偏差。

您所做的工作有所不同,因為您已經還原了步驟2和3:首先,您對所有結果求和,然后對和求平方。 不幸的是,這並不相同,因為(a + b)^ 2 = a ^ 2 + 2ab + b ^ 2顯然不同於a ^ 2 + b ^ 2。 這意味着,當您需要取一些平方的和時,就不能取和的平方。

也就是說,您的代碼有些混亂:

float sum, count,var;
ave=sum/count;

您這里不需要sum ,並且在這種情況下, count是固定的(為5),因此您也不需要。 並且ave作為參數傳遞,因此您不必再次聲明它(也不必對其進行計算-如果您將其作為參數傳遞,則在調用函數之前已經進行了計算!)。

暫無
暫無

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

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