算法競賽入門經典 習題3-1 分數統計 習題 3-2 單詞的長度

習題3-1 分數統計

輸入一些學生的分數,哪個分數出現的次數最多?如果有多個並列,從小到大輸出。
任務1:分數均不超過100的非負整數
任務2:分數均不超過100的非負實數,但最多保留兩位小數。

任務1

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXN 101 + 10
int a[MAXN];

int main(int argc, char *argv[])
{
  
  int n, max = 0, i;
  memset(a, 0, sizeof(a));
  while(scanf("%d", &n) == 1)
  {
     a[n]++;
     if(a[n] > max) max = a[n];
  }
  for(i = 0; i <= 100; i++)
  {
     if(a[i] == max) printf("%d ", i);
  }
  printf("\n");
  memset(a, 0, sizeof(a));
  system("PAUSE");	
  return 0;
}

任務2

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define MAXN 10001 + 10
int a[MAXN];

int main(int argc, char *argv[])
{
  double degree, m;
  int max = 0, i;
  memset(a, 0, sizeof(a));
  while(scanf("%lf", °ree) == 1)
  {
     double m = degree*100;
     int n;
     n = floor(m+0.5);
     a[n]++;
     if(a[n] > max) max = a[n];
  }
  for(i = 0; i <= 10000; i++)
  {
     if(a[i] == max) printf("%.2lf ", i*0.01);
  }
  printf("\n");
 
  system("PAUSE");	
  return 0;
}

總結:任務2   degree設置爲double,然後轉爲int,用floor(m+0.5),以前碰到過,切記


習題3-2 單詞的長度

輸出它們的平均長度。單詞只包含大寫字母和小寫字母,用一個或多個空格隔開。


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXN 100
char a[MAXN];

int main(int argc, char *argv[])
{
  int count = 0;
  float sum = 0;
  while(scanf("%s", a) == 1)
  {
     count++;
     sum += strlen(a);
  }
  
  printf("%.3lf\n", sum/count);
  system("PAUSE");	
  return 0;
}

總結:不知道網上其他的答案爲什麼寫那麼多代碼,有時間要仔細看看
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章