回复 3楼 紫禁
闲着无聊,帮楼主完善了下
其实就是个打印字符长度以及对齐问题,不多说了,看代码,测试通过
程序代码:
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
/*M必须大于1*/
#define M 5
#define N 5
void input(int scores[][3]);
void cal(int scores[][3], double avgR[], double avgC[]);
void sort(double avgR[], int idx[]);
void printstring(char *s, int n); //打印给定长度的字符串
int main(void)
{
char *ke[N] = {"语文","数学","英语","平均分","总分"};
char *names[M] = {"张三", "李四", "王五", "赵六", "田七"};
int scores[M][3] = {0}, idx[M] = {0}, i, j;
double avgR[M] = {0}, avgC[3] = {0};
input(scores);
cal(scores, avgR, avgC);
sort(avgR, idx);
for(j=0;j<N;j++)
{
if(j==0)
printstring(" ",8);
printstring(ke[j],8);
}
printf("\n");
for (i = 0; i < M; i++)
{
printstring(names[i],8);
for (j = 0; j < 3; j++)
{
printf("%3d ", scores[i][j]); //3位数+5个空格
}
printf("%3.1lf ", avgR[i]); //4位数+4个空格
printf("%3.0f \n", avgR[i]*3); //总分=平均分*3
}
getchar();
return 0;
}
void input(int score[][3])
{
int i, j;
for (i = 0; i < M; i++)
for (j = 0; j < 3; j++)
score[i][j] = 40 + rand() % 61;
return;
}
void cal(int scores[][3], double avgR[], double avgC[])
{
int i, j;
for (i = 0; i < M; i++)
{
for (j = 0; j < 3; j++)
{
avgR[i] += scores[i][j];
avgC[j] += scores[i][j];
}
avgR[i] /= 3;
}
for (j = 0; j < 3; j++)
avgC[j] /= M;
return;
}
void sort(double avgR[], int idx[])
{
int i, j;
for (i = 0; i < M; i++)
idx[i] = i;
for (i = 0; i < M - 1; i++)
{
for (j = i + 1; j < M; j++)
if (avgR[i] < avgR[j])
idx[i] = j, idx[j] = i;
}
return;
}
void printstring(char *s, int n)
{
int i=strlen(s),j;
if(i<=n)
{
printf("%s",s);
for(j=0;j<(n-i);j++)
printf(" ");
}
else
printf("%8s",s);
}
图片附件: 游客没有浏览图片的权限,请
登录 或
注册
[
本帖最后由 ggyy4k 于 2011-12-13 23:08 编辑 ]