计算学生成绩:
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <string>
#include <ios>using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::streamsize;
using std::setprecision;int main(int argc, char* argv[])
{
//ask for and read the student's name
cout<<"Please enter your first name: ";
string name;
cin>>name;
cout<<"Hello, "<<name<<"!"<<endl;//ask for and read the midterm and final grades
cout<<"Please enter your midterm and final exam grades: ";
double midterm,final;
cin>>midterm>>final;cout<<"Enter all your homework grades, followed by end of file: ";
int count=0;
double sum=0;double x;
while (cin>>x)
{
count++;
sum += x;
}streamsize prec = cout.precision();
cout << "Your final grade is " << setprecision(3)
<< 0.2 * midterm + 0.4 * final +0.4 * sum / count
<< setprecision(prec) << endl ;return 0;
}
程序中使用 setprecision 来控制输出精度,setprecision在头文件iomanip中;
cout的成员函数precision返回其输出精度,在C++中,默认为6;
不同的C++系统提供给用户的文件结束标志不同,Window操作系统中是:回车键,然后再按z键;
用浮点数时,一般都采用Double型,精度较Float高,速度也不一定慢;
将上面代码中紫色部分替换成下面代码(命名空间改为 using namesapce std;):
加上两个头文件:
#include <vector>
#include <algorithm>
double x;
vector<double> homework;
while (cin>>x)
homework.push_back(x);typedef vector<double>::size_type vec_sz;
vec_sz size = homework.size();if (size == 0)
{
cout<<"You must enter your grades. Please try again."<<endl;
return 1;
}sort(homework.begin(),homework.end());
vec_sz mid=size/2;
double median;
median = size % 2 == 0 ? (homework[mid]+homework[mid-1]) / 2 : homework[mid];streamsize prec = cout.precision();
cout << "Your final grade is " << setprecision(3)
<< 0.2 * midterm + 0.4 * final +0.4 * median
<<setprecision(prec) << endl ;
typedef A B; 定义B与A同义;
vector类型,定义在头文件vector中,是一个标准库类型的容器,可存放指定类型的一连串的值,可动态增长。
vector<double>::size_type 是一个类型,用来保存vector中元素个数;
vector<T> v; 创建一个空的vector,包含的元素类型为T;
v.push_bake(e)、v[i]、v.size()的具体含义(略)
sort(b,e) 对区间[b,e)中的元素非降序排序,定义在头文件algorithm中;
已经有(0)位网友发表了评论,你也评一评吧!
原创文章如转载,请注明:转载自Eddy Blog
原文地址:http://www.rrgod.com/program/308.html 欢迎订阅Eddy Blog。