Problem Description
Each course grade is one of the following five letters: A, B, C, D, and F. (Note that there is no grade E.) The grade A indicates superior achievement , whereas F stands for failure. In order to calculate the GPA, the letter grades A, B, C, D, and F are assigned the following grade points, respectively: 4, 3, 2, 1, and 0.
Input
The input file will contain data for one or more test cases, one test case per line. On each line there will be one or more upper case letters, separated by blank spaces.
Output
Each line of input will result in exactly one line of output. If all upper case letters on a particular line of input came from the set {A, B, C, D, F} then the output will consist of the GPA, displayed with a precision of two decimal places. Otherwise, the message “Unknown letter grade in input” will be printed.
Sample Input
A B C D F
B F F C C A
D C E F
Sample Output
2.00
1.83
Unknown letter grade in input
Author
2006Rocky Mountain Warmup
Source
HDU “Valentines Day” Open Programming Contest 2009-02-14
题目分析
用字符串读入,设有n个字母,那么就有n-1个空格,就可算出一个case里面有多少字母,然后每个去判断,如果有不是来自ABCDF的字母直接跳出循环,不然就按照字母对应的分数算即可
注:偶尔的使用goto语句我觉得没有什么大碍
Code
#include
#include
#include
#include
#include
#include
#include
using namespace std;
typedef __int64 ll;
char s[10001];
char str[6]={'A','B','C','D','F'};
bool find(char c)
{
for(int i=0;i<5;i++)
{
if(c==str[i]) return true;
}
return false;
}
int getNum(char c)
{
switch(c)
{
case 'A':return 4;
case 'B':return 3;
case 'C':return 2;
case 'D':return 1;
case 'F':return 0;
}
}
int main()
{
while(gets(s))
{
int num = (strlen(s)+1)/2; //算出字符个数
double sum = 0.0;
for(int i=0;i<strlen(s);i+=2)
{
if(!find(s[i]))
{
cout<<"Unknown letter grade in input"<goto label; //跳到while循环的最后一个语句
}else
{
sum += getNum(s[i]);
}
}
printf("%.2lf\n",sum/num);
label:;
}
return 0 ;
}
更多问题请关注个人博客,不定时更新