编写一个go语言,、构造一个map以学号为key存储学生信息(姓名、性别、学号、年龄、成绩),产生10个学生信息并存入map,然后将所有学生信息取出,按成绩排序(由高到低)存入一个切片中,然按照顺序输出学生信息
时间: 2023-11-27 09:53:07 浏览: 51
```go
package main
import (
"fmt"
"sort"
)
type student struct {
name string
gender string
id int
age int
score float64
}
func main() {
students := make(map[int]student)
for i := 1; i <= 10; i++ {
students[i] = student{name: fmt.Sprintf("Student%d", i), gender: "Male", id: i, age: 18 + i, score: 60 + float64(i)*5}
}
scores := make([]float64, 0, len(students))
for _, s := range students {
scores = append(scores, s.score)
}
sort.Slice(scores, func(i, j int) bool {
return scores[i] > scores[j]
})
for _, score := range scores {
for _, s := range students {
if s.score == score {
fmt.Printf("name: %s, gender: %s, id: %d, age: %d, score: %.2f\n", s.name, s.gender, s.id, s.age, s.score)
}
}
}
}
```
运行结果:
```
name: Student10, gender: Male, id: 10, age: 28, score: 110.00
name: Student9, gender: Male, id: 9, age: 27, score: 105.00
name: Student8, gender: Male, id: 8, age: 26, score: 100.00
name: Student7, gender: Male, id: 7, age: 25, score: 95.00
name: Student6, gender: Male, id: 6, age: 24, score: 90.00
name: Student5, gender: Male, id: 5, age: 23, score: 85.00
name: Student4, gender: Male, id: 4, age: 22, score: 80.00
name: Student3, gender: Male, id: 3, age: 21, score: 75.00
name: Student2, gender: Male, id: 2, age: 20, score: 70.00
name: Student1, gender: Male, id: 1, age: 19, score: 65.00
```
阅读全文