ACM-HDoj暑假竞赛(7)-1011解题报告

新浪博客 发表时间 -- 2009-07-27 18:37:53

 

题目:

 

      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
算法:
 这题让我提交了很多次,追其原因是因为压根没考虑好,漏了一种情况,一开始还以为数组开得太小呢,后来改了又改,交了又交,还是没A了,题目说的是A代表4分,B代表3分,C代表2分,D代表1分,F代表0分,如果输入的数据不是A,B,C,D,F 中的一个的话就输出Unknown letter grade in input,题目中还刻意强调没有E,还以为测试数据只有A到F之间的字母而已,想法简单的代价就是提交了N次,且都A,郁闷死掉了。。其实这道题目理解了题意就很简单了,可以用switch(...)case(...)结构,也可以用if(...)else(...)选择结构,switch(...)case(...)的比较简便,在这里我用下if(...)else(...)的...代码如下,估计有很多没用的代码..
代码:
 #include "stdio.h"
#include "string"
int main()
{
 char str[10000];
 int a[10000];
 int d,i;
 //freopen("e:\\z1011.txt","r",stdin);
 while (gets(str))
 {
  float t;
  float sum=0,j=1,s1=0;
  memset(a,-1,sizeof(a)); //先给数组赋值为-1
  d=strlen(str);
  for (i=0;i<d;i++)
  {
   if (str[i]=='A')
   {
    a[i]=4;
   }
   if (str[i]=='B')
   {
    a[i]=3;
   }
   if (str[i]=='C')
   {
    a[i]=2;
   }
   if (str[i]=='D')
   {
    a[i]=1;
   }
   if (str[i]=='F')
   {
    a[i]=0;
   }
   if (str[i]==' ') 
   {
    a[i]=0; //把空格等于-1的赋值为0,为下面的相加做准备
   }
  }
  for (i=0;i<d;i++)
  {
   if(a[i]==-1) //不是A,B,C,D,F的情况
   {
    j=0;
    break;
   }
  }
  if (!j)
  {
   printf("Unknown letter grade in input\n");
  }
  else
  {
   for (i=0;i<d;i++)
   {
    sum+=a[i];
   }
   t=sum/(d+1)*2; //一开始数组的长度也有把空格算进去
   printf("%0.2f\n",t); 
  }
 }
 return 0;
}

你可能感兴趣的:(c,算法,input,each,float,output)