第14周报告2:
实验目的:学会使用循环控制语句解决实际问题
实验内容:用循环控制语句编写程序,完成表达式的计算
/* 程序头部注释开始
* 程序的版权和版本声明部分
* Copyright (c) 2011, 烟台大学计算机学院学生
* All rights reserved.
* 文件名称: 小组成绩的输入与输出
* 作 者: 2011级 114-3 张宗佳
* 完成日期: 2011 年 11 月 25 日
* 版本号: vc.3
* 对任务及求解方法的描述部分
* 输入描述:学生人数和成绩
* 问题描述:(函数及数组的简单应用) 在数组score中将要存储某小组C++程序设计的成绩,请设计完成下面功能函数,并将它们组合成一个完整的应用:
(1)输入小组人数及成绩;
(2)输出该小组的最高成绩、最低成绩、平均成绩和成绩的标准偏差;
(3)输出考得最高成绩和最低成绩的同学的人数及对应的学号(设成绩对应的下标即学号,可能有相同的成绩)
* 程序输出:小组的最高成绩、最低成绩、平均成绩和成绩的标准偏差;最高成绩和最低成绩的同学的人数及对应的学号
* 问题分析:……
* 算法设计:……
*/
#include <iostream>
#include<Cmath>
using namespace std;
//在这个问题中,成绩和人数是核心数据,适合作为全局变量处理
int score[50]; //将score设为全局变量,在各个函数中可以直接使用
int num; //小组人数也设为全局变量
void input_score();
int get_max_score();
int get_min_score();
double get_avg_score();
double get_stdev_score();
int count(int);
void output_index(int);
int main(void)
{
int max_score,min_score;
cout << "小组共有多少名同学?";
cin >> num;
cout << endl << "请输入学生成绩:" << endl;
input_score(); //要求成绩在0-100之间
max_score=get_max_score();
cout << endl << "最高成绩为:" << max_score << ",共有 " << count(max_score ) << " 人。";
min_score=get_min_score();
cout << endl << "最低成绩为:" << min_score << ",共有 " << count(min_score ) << " 人。";
cout << endl << "平均成绩为:" << get_avg_score();
cout << endl << "标准偏差为:" << get_stdev_score();
cout << endl << "获最高成绩的学生(学号)有:";
output_index(max_score);
cout << endl << "获最低成绩的学生(学号)有:";
output_index(min_score);
cout << endl;
system("PAUSE");
return 0;
}
// input_score函数提供给同学们参考
//input_score函数的功能是输入小组成员的成绩
void input_score()
{
int i;
for(i = 0; i < num; i++)
{
do
{
cout << "输入第 " << i << " 位同学的成绩:";
cin >> score[i];
}while(score[i] < 0 || score[i] > 100);
}
return;
}
// get_max_score()函数的功能是求出num名同学的最高成绩
int get_max_score()
{
int i, max = score[0];
for (i = 1; i < num; i++)
{
if(max < score[i])
{
max = score[i];
}
}
return max;
}
// get_min_score()函数的功能是求出num名同学的最低成绩
int get_min_score()
{
int i, t = 101;
for(i = 0; i < num; i++)
{
if(t > score[i])
{
t = score[i];
}
}
return t;
}
// get_avg_score()函数的功能是求出num名同学的平均成绩
double get_avg_score()
{
int i;
double sum = 0, a;
for(i = 0; i < num; i++)
{
sum = sum + score[i];
}
a = sum/num;
return a;
}
// get_ stdev _score()函数的功能是求出num名同学成绩的标准偏差
double get_stdev_score()
{
int i;
double stdev, sum = 0, x;
x=get_avg_score();
for(i = 0; i < num; i++)
{
sum = sum + (score[i] - x) * (score[i] - x);
}
stdev = sqrt(sum)/(num-1);
return stdev ;
}
// count(int s)函数的功能是返回值score数组中为s的元素的个数
int count(int s)
{
int n = 0,i;
for(i = 0; i < num; i++)
{
if(s == score[i])
{
n++;
}
}
return n;
}
// output_index函数的功能是输出score数组中值为s的元素的下标(index)
//注意:值为s的元素可能有多个
void output_index(int s)
{
int i;
for(i = 0; i < num; i++)
{
if(s == score[i])
cout << i << '\t';
}
return ;
}
经验积累:
1.在声明函数时,如果函数的括弧里没有定义类型,那么在后面定义函数的时候也不用定义类型,如在这里声明了函数int get_max_score()那么在后面定义式也要int get_max_score()而不用在括弧里再定义(int x)之类的变量了。
2.定义的数组score[i]的下标i必须是整型的常量或常量表达式,而不能是其它类型总不能有第9.5个数吧...
上机感言:编的程序比原来又长了,但只是编的自定义的函数,如果让我编主函数的话还真不一定能编出来.. 但不管怎么说这次的报告比上周用的时间短哦~虽然也不容易,但是真好,终于又编出一个...