#include<stdio.h> #include<string.h> void+sort(int+**p
时间: 2023-11-23 18:06:44 浏览: 77
这是一个使用指针实现的简单排序程序,可以对输入的整数进行排序并输出。程序中定义了一个指向指针的指针p和一个指针数组pstr,pstr中存放的是指向整型变量的指针。程序首先输入n,然后将pstr数组中的每个元素指向str数组中的对应元素,接着输入n个整数,将每个整数存放在str数组中。然后将p指向pstr,调用sort函数进行排序,最后输出排序后的结果。
sort函数中使用了双重指针来实现对指针数组的排序,temp是一个指向整型变量的指针,用于交换两个指针数组元素的值。在sort函数中,使用了两层循环来实现冒泡排序,比较相邻两个元素的大小,如果前
相关问题
#include<stdio.h> #include<string.h> typedef struct date { int year; int month; int day; }DATE; typedef struct student { int num; char name[20]; char sex; DATE birthday; float score; }STUDENT; void input(STUDENT *s); void output(STUDENT s); /********** Begin **********/ /********** End **********/
完整代码如下所示:
```c
#include <stdio.h>
#include <string.h>
typedef struct date {
int year;
int month;
int day;
} DATE;
typedef struct student {
int num;
char name[20];
char sex;
DATE birthday;
float score;
} STUDENT;
void input(STUDENT *s);
void output(STUDENT s);
void sort(STUDENT s[], int n);
int main() {
STUDENT s[5];
int i;
for (i = 0; i < 5; i++) {
printf("请输入第%d个学生的信息:\n", i + 1);
input(&s[i]);
}
sort(s, 5);
printf("\n排序后的学生信息为:\n");
for (i = 0; i < 5; i++) {
output(s[i]);
}
return 0;
}
void input(STUDENT *s) {
printf("学号:");
scanf("%d", &s -> num);
printf("姓名:");
scanf("%s", s -> name);
printf("性别:");
scanf(" %c", &s -> sex);
printf("生日:");
scanf("%d/%d/%d", &s -> birthday.year, &s -> birthday.month, &s -> birthday.day);
printf("成绩:");
scanf("%f", &s -> score);
}
void output(STUDENT s) {
printf("学号:%d,姓名:%s,性别:%c,生日:%d/%d/%d,成绩:%.2f\n",
s.num, s.name, s.sex, s.birthday.year, s.birthday.month, s.birthday.day, s.score);
}
void sort(STUDENT s[], int n) {
int i, j;
STUDENT temp;
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (s[i].score < s[j].score) {
temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
}
}
```
这段代码中,定义了一个main函数,用于程序的入口,创建了一个学生信息数组s。在main函数中,使用for循环对每个学生的信息进行输入。输入完成后,调用sort函数对学生信息数组s进行排序。最后,使用for循环对排序后的学生信息进行输出。
#include <stdio.h> #include <string.h> #define n 100 int main(void) { //*****begin******** char a[100]; int x,i,j,temp; scanf("%s",a); x=strlen(a); for(i=1;i<=x-1;i++) { for(j=1;j<=n-i;j++) { if (a[j-1]<a[j]) { temp=a[j-1]; a[j-1]=a[i]; a[i]=temp; } } } a[x]='\0'; printf("%s",a); //*****end****** return 0; }
这段代码使用了冒泡排序(Bubble Sort)来对输入的字符串进行排序。但是,代码中存在一些问题,导致无法正确排序。以下是修改后的代码:
```c
#include <stdio.h>
#include <string.h>
#define n 100
int main(void) {
char a[100];
int x, i, j, temp;
scanf("%s", a);
x = strlen(a);
for (i = 0; i < x-1; i++) { // 修改了循环条件
for (j = 0; j < x-i-1; j++) { // 修改了循环条件
if (a[j] < a[j+1]) { // 修改了比较条件
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
a[x] = '\0';
printf("%s", a);
return 0;
}
```
在这个修改后的代码中,我们将循环条件以及比较条件都进行了修改。使用此代码,您可以正确地对输入的字符串进行排序。希望这可以帮助到您!