- 论坛徽章:
- 0
|
本帖最后由 ZZZZZZ~ 于 2012-04-11 16:37 编辑
main的长度请不要批了。- #include <stdio.h>
- #include <stdlib.h>
- typedef struct
- {
- size_t index;
- size_t count;
- float aver_score;
- } CMP_INDEX_T;
- int cmp(const void *a, const void *b)
- {
- const CMP_INDEX_T *ia = (const CMP_INDEX_T *)a;
- const CMP_INDEX_T *ib = (const CMP_INDEX_T *)b;
-
- if(ia->aver_score < ib->aver_score)
- return -1;
- else if(ia->aver_score == ib->aver_score)
- return 0;
- else
- return 1;
- }
- float get_aver(const unsigned char *st, size_t count)
- {
- float total = 0;
- for(size_t i = 0; i < count; ++i)
- total += *st++;
- return (count == 0 ? 0 : total/count);
- }
- int main()
- {
- const size_t CLASS_NUM = 3;
- const size_t ST_NUM = 100;
- // 定义保存批量数据的二维数组,
- unsigned char scores[CLASS_NUM][ST_NUM];
- // 排序索引
- CMP_INDEX_T cmp_index[CLASS_NUM];
- // 利用for语句完成数据的输入
- for(size_t i = 0; i < CLASS_NUM; ++i)
- {
- printf("please input the scores of class %d, with 0 terminated:\n", i+1);
- size_t j;
- for(j = 0; j < ST_NUM; ++j)
- {
- // 将输入的数据保存到scores[i][j]
- int score;
- while(1)
- {
- // scanf真难用!
- int ret = scanf("%d", &score);
- if(ret < 0)
- {
- fprintf(stderr, "input failed\n");
- return 1;
- }
- else if(ret == 0)
- {
- scanf("%*s");
- fprintf(stderr, "Try to input again, (score >= 0 and <= 100)\n");
- }
- else if(score < 0 || score > 100)
- {
- printf("score = %d\n", score);
- fprintf(stderr, "Try to input again, (score >= 0 and <= 100)\n");
- }
- else break; // 输入OK
- }
-
- if(score == 0)
- break; // 本组输入完成
- else
- scores[i][j] = (unsigned char)score;
- }
-
- //填入索引和平均值
- cmp_index[i].count = j;
- cmp_index[i].index = i;
- cmp_index[i].aver_score = get_aver(scores[i], j);
- }
-
- //排序
- puts("sort");
- qsort(cmp_index, CLASS_NUM, sizeof(cmp_index[0]), cmp);
- puts("end");
-
- //输出
- for(size_t i = 0; i < CLASS_NUM; ++i)
- {
- printf("average score is %.2f :\n", cmp_index[i].aver_score);
-
- unsigned char *st = scores[cmp_index[i].index];
- for(size_t j = 0; j < cmp_index[i].count; ++j)
- printf("%4d", *st++);
- printf("\n");
- }
-
- return 0;
- }
复制代码 |
|