【发布时间】:2015-03-05 21:13:59
【问题描述】:
我正在尝试计算 txt 文件中学生的标准差和平均值。我的平均值下降了,但我无法使用函数计算 5 个等级的标准差。我的原型是 无效统计(双,双,双,双,双,双&ave,双&sd); 我被困在这一点上。我不知道输出我的标准偏差或者我是否有我的 void 函数。谢谢
#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);
}
【问题讨论】:
-
只需实现简单的方程式 - 它广为人知,可以用谷歌搜索
-
你可以使用
std::vector吗?向量将使平均偏差和标准偏差更容易实现。 -
@ThomasMatthews 不,我们还没有这样做。
-
你需要给
sum和count赋值。考虑到你所拥有的,两者都很容易。 -
你不能从你声明返回
void的函数返回值。 (要么返回答案,要么将其分配给sd- 不是两者。)