身高测量是日常生活中的常见需求,如体育训练、健康检查等。然而,如何快速、准确地测量并排列一组人的身高,却是一个不小的挑战。本文将介绍如何利用C语言编程,轻松实现精确的身高测量与排列。
首先,我们需要定义一个结构体来存储身高数据。以下是一个简单的身高数据结构:
#include <stdio.h>
#define MAX_PEOPLE 100
typedef struct {
char name[50];
int height;
} Person;
接下来,我们需要编写一个函数来输入身高数据。以下是一个示例:
void input_data(Person people[], int *count) {
printf("请输入人数(不超过%d):", MAX_PEOPLE);
scanf("%d", count);
for (int i = 0; i < *count; i++) {
printf("请输入第%d个人的姓名和身高:", i + 1);
scanf("%s %d", people[i].name, &people[i].height);
}
}
为了对身高进行排序,我们可以使用冒泡排序算法。以下是一个简单的冒泡排序函数:
void sort_people(Person people[], int count) {
for (int i = 0; i < count - 1; i++) {
for (int j = 0; j < count - i - 1; j++) {
if (people[j].height > people[j + 1].height) {
Person temp = people[j];
people[j] = people[j + 1];
people[j + 1] = temp;
}
}
}
}
最后,我们需要编写一个函数来输出排序后的身高数据:
void output_data(Person people[], int count) {
printf("排序后的身高数据如下:\n");
for (int i = 0; i < count; i++) {
printf("%s: %dcm\n", people[i].name, people[i].height);
}
}
以下是完整的C语言程序:
#include <stdio.h>
#define MAX_PEOPLE 100
typedef struct {
char name[50];
int height;
} Person;
void input_data(Person people[], int *count);
void sort_people(Person people[], int count);
void output_data(Person people[], int count);
int main() {
Person people[MAX_PEOPLE];
int count = 0;
input_data(people, &count);
sort_people(people, count);
output_data(people, count);
return 0;
}
void input_data(Person people[], int *count) {
printf("请输入人数(不超过%d):", MAX_PEOPLE);
scanf("%d", count);
for (int i = 0; i < *count; i++) {
printf("请输入第%d个人的姓名和身高:", i + 1);
scanf("%s %d", people[i].name, &people[i].height);
}
}
void sort_people(Person people[], int count) {
for (int i = 0; i < count - 1; i++) {
for (int j = 0; j < count - i - 1; j++) {
if (people[j].height > people[j + 1].height) {
Person temp = people[j];
people[j] = people[j + 1];
people[j + 1] = temp;
}
}
}
}
void output_data(Person people[], int count) {
printf("排序后的身高数据如下:\n");
for (int i = 0; i < count; i++) {
printf("%s: %dcm\n", people[i].name, people[i].height);
}
}
通过以上C语言编程方法,我们可以轻松实现身高数据的测量、排序和输出。在实际应用中,可以根据需求对程序进行扩展和优化,例如添加数据持久化功能、用户界面等。
版权声明:如发现本站有侵权违规内容,请发送邮件至yrdown@88.com举报,一经核实,将第一时间删除。
公安部网络违法犯罪举报网站 蜀ICP备2024051011号