25行代码AC_HDU - 4802 GPA(浮点数的运算)

Problem Description

In college, a student may take several courses. for each course i, he earns a certain credit (ci), and a mark ranging from A to F, which is comparable to a score (si), according to the following conversion table
在这里插入图片描述

The GPA is the weighted average score of all courses one student may take, if we treat the credit as the weight. In other words,

在这里插入图片描述

An additional treatment is taken for special cases. Some courses are based on “Pass/Not pass” policy, where stude nts earn a mark “P” for “Pass” and a mark “N” for “Not pass”. Such courses are not supposed to be considered in computation. These special courses must be ignored for computing the correct GPA.
Specially, if a student’s credit in GPA computation is 0, his/her GPA will be “0.00”.

Input

There are several test cases, please process till EOF.
Each test case starts with a line containing one integer N (1 <= N <= 1000), the number of courses. Then follows N lines, each consisting the credit and the mark of one course. Credit is a positive integer and less than 10.

Output

For each test case, print the GPA (rounded to two decimal places) as the answer.


思路分析:

题意:求GPA,公式直接给我们了,需要注意的是若字母为P或者N,需要直接忽略。

有一个注意点是:浮点数没办法直接比较, 如:3.1-0.2 不等于 2.9。 因为每个浮点数都是不精确的,小数点后几十位很可能就是乱序的数字。在比较时它们也会被算进去。

解决办法:采用区间判定的方法。如:若浮点型变量mol满足:mol>=(-1e-6)&&mol<=(1e-6)则它一定等于0。

接下来展示代码:

#include<bits/stdc++.h>
using namespace std;
int main( ) {
    
    
	int n; while(cin>>n) {
    
    
		double x; string c; 
		double mol = 0, demo= 0; 	//分子和分母 
		for(int i = 0; i < n; i++) {
    
    
			cin>>x>>c;
			if(c=="A") {
    
     mol += (x*4.0);  demo+=x; }
			if(c=="A-") {
    
    mol += (x*3.7);  demo+=x; }
			if(c=="B+"){
    
     mol += (x*3.3);  demo+=x; }
			if(c=="B") {
    
    mol += (x*3.0);  demo+=x; }
			if(c=="B-") {
    
    mol += (x*2.7);  demo+=x; }
			if(c=="C+") {
    
    mol += (x*2.3);  demo+=x; }
			if(c=="C") {
    
    mol += (x*2.0);  demo+=x; }
			if(c=="C-") {
    
    mol += (x*1.7);  demo+=x; }
			if(c=="D") {
    
    mol += (x*1.3);  demo+=x; }
			if(c=="D-") {
    
    mol += (x*1.0);  demo+=x; }
			if(c=="F") {
    
    mol += (x*0);  demo+=x; }
		}
		if(mol>=(-1e-6)&&mol<=(1e-6)) {
    
     cout <<"0.00"<< endl; continue; }
		else printf("%.2lf\n", (mol/demo));
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43899069/article/details/108277331
今日推荐