发布时间:2023-08-12 09:30
//有个bug,学号个位数,不输出姓名。
#include
#include
#define NUM 3
int find_num(int num[], int target)
{
int left = 0;
int right = NUM-1;//最后一个元素的索引
while (left <= right)//左闭右闭区间 ->[left,right]
{
int mid = left + (right - left) / 2;//为了防止溢出,(right + left ) / 2可能会溢出
if (num[mid] == target)
{
return mid;//找到指定数就立即返回
}
else if (num[mid] > target)
right = mid - 1;
else if (num[mid] < target)
left = mid + 1;
}
return -1;
}
int main()
{
int i, j, tmp3,target;
char name[NUM][10];//姓名
int num[NUM];//学号
float score[NUM][3];//三门课成绩
float sum[NUM];//总成绩
float tmp, tmp0, tmp1, tmp2;
char stmp[10];
int find_num(int num, int target);
printf("输入姓名、学号和三门课成绩:\n");
for (i = 0; i < NUM; i++)
{
printf("请输入第%d个学生的信息:\n", i);
scanf(" %s %d %f %f %f", name[i], &num[i], &score[i][0], &score[i][1], &score[i][2]);
getchar();
sum[i] = score[i][0] + score[i][1] + score[i][2];
}
for (i = 0; i < NUM - 1; i++)
{
for (j = i + 1; j < NUM; j++)
{
if (num[i] < num[j])
{
tmp0 = score[i][0];
score[i][0] = score[j][0];
score[j][0] = tmp0;//交换成绩
tmp1 = score[i][1];
score[i][1] = score[j][1];
score[j][1] = tmp1;//交换成绩
tmp2 = score[i][2];
score[i][2] = score[j][2];
score[j][2] = tmp2;//交换成绩
tmp = sum[i];
sum[i] = sum[j];
sum[j] = tmp;//交换成绩
tmp3 = num[i];
num[i] = num[j];
num[j] = tmp3;//交换成绩
strcpy(stmp, name[i]);
strcpy(name[i], name[j]);
strcpy(name[j], stmp);//交换姓名
}
}
}
printf("排序后的学生的信息:\n");
for (i = 0; i < NUM; i++)
{
printf("%s\t%d\t%f\t%f\t%f\n", name[i], num[i], score[i][0], score[i][1], score[i][2]);
}
scanf("%d", &target);
target=find_num(num,target);
printf("%s",name[target]);
system("pause");
return 0;
}