1.題目:輸入4個人的名字(一個英文字母)和成績,最後顯示最高分與最低分的分數和名字
2.程式碼
# include <stdio.h>
main()
{
float a[4];
int i;
int j;
float k;
float Ave = 0;
char b[4][2];
char l;
for(i = 0; i < 4; i = i + 1)
scanf("%s %f", &b[i], &a[i]);
for(i = 0; i < 4; i = i + 1)
for(j = 0; j < (4 - i) - 1; j = j + 1)
{
if(a[j] > a[j + 1])
{
k = a[j];
a[j] = a[j + 1];
a[j + 1] = k;
l = b[j][2];
b[j][2] = b[j + 1][2];
b[j + 1][2] = l;
}
}
for(i = 0; i < 4; i = i + 1)
Ave = Ave + a[i];
Ave = Ave / 4;
printf("Max = %.2f %s\n", a[3], b[3]);
printf("min = %.2f %s\n", a[0], b[0]);
printf("Ave = %.2f\n", Ave);
}
3.顯示畫面
4.問題:請問要怎麼使最高分是f,最低分是v?
排序的地方小改一下即可
# include <stdio.h>
int main()
{
float a[4];
int i;
int j;
float k;
float Ave = 0;
char b[4][2];
char l;
for(i = 0; i < 4; i = i + 1)
scanf("%s %f", &b[i], &a[i]);
for(i = 0; i < 4; i = i + 1)
for(j = 0; j < (4 - i) - 1; j = j + 1)
{
if(a[j] > a[j + 1])
{
k = a[j];
a[j] = a[j + 1];
a[j + 1] = k;
// l = b[j][2];
// b[j][2] = b[j + 1][2];
// b[j + 1][2] = l;
l = b[j][0];
b[j][0] = b[j + 1][0];
b[j + 1][0] = l;
l = b[j][1];
b[j][1] = b[j + 1][1];
b[j + 1][1] = l;
}
}
for(i = 0; i < 4; i = i + 1)
Ave = Ave + a[i];
Ave = Ave / 4;
printf("Max = %.2f %s\n", a[3], b[3]);
printf("min = %.2f %s\n", a[0], b[0]);
printf("Ave = %.2f\n", Ave);
}
首先不知道你為什麼要宣告為char b[4][2]
,看起來沒有用到,所以我擅自把它拿掉改為char b[4]
,所以回圈內的那個[2]
也可以拿掉了,另外要提醒的是printf("Max = %.2f %s\n", a[3], b[3]);
內的%s
是給一個字串,但b[3]
是字元,所以應該改為%c,若
引用錯誤很可能造成Access violation reading location 0x00000066.
改完如下
# include <stdio.h>
main()
{
float a[4];
int i;
int j;
float k;
float Ave = 0;
char b[4];
char l;
for (i = 0; i < 4; i = i + 1)
scanf("%s %f", &b[i], &a[i]);
for (i = 0; i < 4; i = i + 1)
for (j = 0; j < (4 - i) - 1; j = j + 1)
{
if (a[j] > a[j + 1])
{
k = a[j];
a[j] = a[j + 1];
a[j + 1] = k;
l = b[j];
b[j] = b[j + 1];
b[j + 1] = l;
}
}
for (i = 0; i < 4; i = i + 1)
Ave = Ave + a[i];
Ave = Ave / 4;
printf("Max = %.2f %c\n", a[3], b[3]);
printf("min = %.2f %c\n", a[0], b[0]);
printf("Ave = %.2f\n", Ave);
}
輸出
k 85
v -5
f 89
d 10
Max = 89.00 f
min = -5.00 v
Ave = 44.75
新增1-以字串處理方式
# include <stdio.h>
main()
{
float a[4];
int i;
int j;
float k;
float Ave = 0;
char b[4][2];
char l;
for (i = 0; i < 4; i = i + 1)
scanf("%s %f", &b[i][0], &a[i]); // 名字存到b[i][0],'\0'會存到b[i][1]
for (i = 0; i < 4; i = i + 1)
for (j = 0; j < (4 - i) - 1; j = j + 1)
{
if (a[j] > a[j + 1])
{
k = a[j];
a[j] = a[j + 1];
a[j + 1] = k;
// b[j][1]都是'\0'
// 只需換名字就好 因此只須換b[j][0]與b[j+1][0]
l = b[j][0];
b[j][0] = b[j + 1][0];
b[j + 1][0] = l;
}
}
for (i = 0; i < 4; i = i + 1)
Ave = Ave + a[i];
Ave = Ave / 4;
printf("Max = %.2f %s\n", a[3], &b[3][0]); // %s要給字串的指標 所以用&
printf("min = %.2f %s\n", a[0], &b[0][0]); // %s要給字串的指標 所以用&
printf("Ave = %.2f\n", Ave);
}
l = b[j][2];
b[j][2] = b[j + 1][2];
b[j + 1][2] = l;
這蠻有趣的,
宣告b[4][2]應該只會有b[j][0]跟b[j][1]而已吧,
所以b[j][2]是跑到下一個記憶體位置了?
變成b[j+1][0]的位置??
可以將成績讀進來就直接處理:
for (i = 0; i < 4; i = i + 1)
{
scanf("%s %f", &b[i], &a[i]);
SUM=SUM+a[i];
if(a[i]>MAX)
MAX=i;
if(a[i]<MIN)
MIN=i;
}