我需要根據他們的姓氏對學生進行排序,或者他們的姓氏是否按照他們的名字按字典順序排列。
#include <stdio.h>
struct Student {
char name[20], surname[20];
};
void sort(struct Student students[], int n) {
int i, j, temp;
for (i = 0; i < n; i )
for (j = i 1; j < n; j )
if (students[j].surname > students[i].surname ||
students[j].name > students[i].name) {
temp = i;
students[i] = students[j];
students[j] = students[temp];
}
}
void main() {
struct Student students[6] = {
{"Mujo", "Mujic"},
{"Meho", "Mujic"},
{"Pero", "Peric"},
{"Beba", "Bebic"},
{"Mujo", "Mujic"},
{"Fata", "Fatic"},
};
sort(students, 6);
int i;
for (i = 0; i < 6; i )
printf("%s %s\n", students[i].surname, students[i].name);
}
這只會列印一個學生六次。你能幫我解決這個問題嗎?
- 注意:不允許使用輔助陣列
uj5u.com熱心網友回復:
你的交換代碼是可疑的——我相信是壞的。一個大的警鐘是型別temp——它需要是一個struct Student.
你有:
temp = i;
students[i] = students[j];
students[j] = students[temp];
你需要:
struct Student temp = students[i];
students[i] = students[j];
students[j] = temp;
顯然,也洗掉定義int temp;。
但是,也存在其他問題(一如既往)。您無法使用關系運算子有效地比較字串 - 使用strcmp(). 而且您的訂購測驗也是錯誤的,即使修改為使用strcmp().
這段代碼完成了這項作業,按降序對名稱進行排序:
#include <stdio.h>
#include <string.h>
struct Student
{
char name[20];
char surname[20];
};
static void sort(struct Student students[], int n)
{
for (int i = 0; i < n; i )
{
for (int j = i 1; j < n; j )
{
int rc = strcmp(students[j].surname, students[i].surname);
if (rc > 0 ||
(rc == 0 && strcmp(students[j].name, students[i].name) > 0))
{
struct Student temp = students[i];
students[i] = students[j];
students[j] = temp;
}
}
}
}
static void dump_array(const char *tag, size_t size, const struct Student *students)
{
printf("%s (%zu):\n", tag, size);
for (size_t i = 0; i < size; i )
printf("%s %s\n", students[i].surname, students[i].name);
}
int main(void)
{
struct Student students[] =
{
{"Mujo", "Mujic"},
{"Meho", "Mujic"},
{"Pero", "Peric"},
{"Zebra", "Elephant"},
{"Beba", "Bebic"},
{"Mujo", "Mujic"},
{"Abelone", "Shells"},
{"Fata", "Fatic"},
};
enum { NUM_STUDENTS = sizeof(students) / sizeof(students[0]) };
dump_array("Before", NUM_STUDENTS, students);
sort(students, NUM_STUDENTS);
dump_array("After", NUM_STUDENTS, students);
return 0;
}
輸出:
Before (8):
Mujic Mujo
Mujic Meho
Peric Pero
Elephant Zebra
Bebic Beba
Mujic Mujo
Shells Abelone
Fatic Fata
After (8):
Shells Abelone
Peric Pero
Mujic Mujo
Mujic Mujo
Mujic Meho
Fatic Fata
Elephant Zebra
Bebic Beba
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/448822.html
