zoey
点击国内主页可以让浏览速度加快哦 ~ !

关于HDOJ 1202题(绩点计算) 的理解(C/C++)

2019-08-10 hdoj cout输出格式 粗心 细节
Word count: 850 | Reading time: 3min

    题目有很多的小细节,一不注意就容易中招。感谢 摆渡过江 的代码点醒。
    首先,区间不是全整数,而是存在有小数的分数情况的,并且,举例来说,如89.9是属于3点绩点。
    再然后是,缺考情况不能把学分加和,可能脑袋有点晕了,之前WA代码就是不管三七二十一,直接把所有学分加和了。


题目描述

The calculation of GPA

Problem Description 每学期的期末,大家都会忙于计算自己的平均成绩,这个成绩对于评奖学金是直接有关的。国外大学都是计算GPA(grade point average) 又称GPR(grade point ratio),即成绩点数与学分的加权平均值来代表一个学生的成绩的。那么如何来计算GPA呢?

一般大学采用之计分法

A90 - 100 4 点
B80 - 89 3 点
C70 - 79 2 点
D60 - 69 1 点
E0 - 59 0 点

例如:某位学生修习三门课,其课目、学分及成绩分别为:
英文:三学分、92 分;化学:五学分、80 分;数学:二学分、60分,则GPA的算法如下:

科目 学分 分数 点数 分数×点数
英文 3 92 4 12
化学 5 80 3 15
数学 2 60 1 2
合计 10 29
29/10=2.9
2.9即为某生的GPA
下面有请你写一个用于计算GPA的程序。

Input
包含多组数据,每组数据的第一行有一个数N,接下来N行每行表示一门成绩。每行有两个实型的数 s,p,s表示这门课的学分,p表示该学生的成绩(百分制)。如果p=-1则说明该学生这门课缺考,是不应该计算在内的。

Output
对每组数据输出一行,表示该学生的GPA,保留两位小数。如果GPA不存在,输出-1。

Sample Input
3
3 92
5 80
2 60

Sample Output
2.90

Author
Speakless



原题链接

More info:Question



cout控制小数点后位数(复习)

头文件为:iomanip

函数为:fixed << setprecision(n)

控制输出小数点后第n位:

1
2
#include<iomanip>
cout << fixed << setprecision(n) << 变量<< endl;

Accepted代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include<iostream>
#include<iomanip>
using namespace std;
int n;
double s, p;
double sum_s, sum_sp;
int main() {
while (cin >> n) {
sum_s = sum_sp = 0.0;//学分总和 学分*点数总和
while (n--)
{
cin >> s >> p;
if ((int)p + 1 == 0) //缺考
continue;
sum_s += s;
if (p >= 90)
sum_sp += 4 * s;
else if (p >= 80)
sum_sp += 3 * s;
else if (p >= 70)
sum_sp += 2 * s;
else if (p >= 60)
sum_sp += s;

}
if (sum_s != 0)
cout << fixed << setprecision(2) << sum_sp / sum_s << endl;
else
cout << -1 << endl;
}

return 0;
}



参考博客

我的AC代码和参考博客的代码差不多,只是习惯了用c++的输入输出,以下是 摆渡过江 老哥的代码(c语言):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>  
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <vector>
using namespace std;

int main()
{
int n;
double s,p;
double sum1,sum2;
while(scanf("%d",&n)!=EOF)
{
sum1=sum2=0.0;
while(n--)
{
scanf("%lf%lf",&s,&p);
if((int)p+1==0)
continue;
sum1+=s;
if(p>=90)
sum2+=4*s;
else if(p>=80)
sum2+=3*s;
else if(p>=70)
sum2+=2*s;
else if(p>=60)
sum2+=s;

}
if(sum1!=0)
printf("%.2lf\n",sum2/sum1);
else
printf("-1\n");
}

return 0;


}






Author: Zoey

Link: https://zoey1038569979.github.io/2019/08/10/hdoj1202/

Copyright: All articles in this blog are licensed under CC BY-NC-SA 3.0 unless stating additionally.

< PreviousPost
关于HDOJ 1205题(吃糖果) 的理解(C/C++)
NextPost >
关于HDOJ 1201题(18岁生日) 的理解(C/C++)
CATALOG
  1. 1. 题目描述
  2. 2. 原题链接
  3. 3. cout控制小数点后位数(复习)
  4. 4. Accepted代码
  5. 5. 参考博客