通过反斜杆零和结构体的值为零反推冒泡的交换轮数

编程入门 行业动态 更新时间:2024-10-07 14:25:48

通过反<a href=https://www.elefans.com/category/jswz/34/1155627.html style=斜杆零和结构体的值为零反推冒泡的交换轮数"/>

通过反斜杆零和结构体的值为零反推冒泡的交换轮数

 通过反斜杆零和结构体的值为零反推出冒泡的交换轮数。

'\0'作为字符串的结束标志,在字符串的最后,这里以*(p+i+1)作为外层循环的判断条件。(p+i+1)!=‘\0’与*(p+i)!='\0'相比,前者是从第二位开始判断,后者是从开头就进入判断,相比之前*(p+i+1)比*(p+i)少了一次的判断条件,即少进入外循环一次,与之前通过数组元素个数减一达到的效果是一样的。

内层循环要想将已经交换到后面的内容固定不再参与交换的话,则需要在外层循环的基础上,通过内容+i,从而减少内层循环与j有关内容的交换。

#include <stdio.h>
#include <malloc.h>
int main()
{int i,j;char *p=NULL;char temp;//是进行字符串的交换,所以定义char类型的temp用以冒泡交换p=malloc(sizeof(char)*27);scanf("%s",p);for(i=0;*(p+i+1)!='\0';i++)//这里,以不等于反斜杆0为循环条件,通过从最后的'\0'倒推交换的轮数{for(j=0;*(p+j+1+i)!='\0';j++){if((*(p+j))<(*(p+j+1)))	{temp=*(p+j);*(p+j)=*(p+j+1);*(p+j+1)=temp;}}}printf("%s",p);	return 0;
}

这里通过先是对结构数组进行初始化为0。这里与通过字符串最后的反斜杆零倒推出冒泡轮数是一个道理。外层循环通过对元素下标进行加一从而跳过第一个元素进行判断,从而减少外层循环的轮数。内层给下标加i,用以固定后面已经交换好的与j相关的内容。

#include <stdio.h>
typedef struct{int num;char name[20];struct socre{float ch;float math;float eng;};float avg;
}Mem_info;
Mem_info student[6]={0}//对结构体进行初始化;
int i;void sto()
{printf("请依次输入5名同学的学号,姓名,三门课的成绩\n");for(i=0;i<5;i++){scanf("%d%s%f%f%f",&student[i].num,student[i].name,&student[i].ch,&student[i].math,&student[i].eng);student[i].avg=(student[i].ch+student[i].math+student[i].eng)/3;}	
}void print(FILE *pf)
{for(i=0;student[i].num!=0;i++)fprintf(pf,"学号%d 姓名%s 语文%.1f 数学%.1f 英语%.1f 平均分%.1f\n",student[i].num,student[i].name,student[i].ch,student[i].math,student[i].eng,student[i].avg);	
}void sort()
{int j;Mem_info temp;for(i=0;student[i+1].num!=0;i++)//这里是通过最后值是否为0来倒推确定交换的轮数{for(j=0;student[j+1+i].num!=0;j++)//内层需要加i而不是减i,通过加i从而将交换倒后面的内容固定下,不再进行多余的交换{if(student[j].avg<student[j+1].avg){temp=student[j];student[j]=student[j+1];student[j+1]=temp;}}}	}void add()
{for(i=5;i<6;i++){scanf("%d%s%f%f%f",&student[i].num,student[i].name,&student[i].ch,&student[i].math,&student[i].eng);student[i].avg=(student[i].ch+student[i].math+student[i].eng)/3;}	
}int main()
{	sto();FILE *pf=NULL;pf=fopen("stud.txt","w"); print(pf);fclose(pf);sort();pf=fopen("stu.sort.txt","w");print(pf);fclose(pf);printf("请输入需要添加人员的信息:\n");add();sort();pf=fopen("stu_sort.txt","w");print(pf);fclose(pf);return 0;
}

更多推荐

通过反斜杆零和结构体的值为零反推冒泡的交换轮数

本文发布于:2024-02-28 05:32:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1768472.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:斜杆   值为   结构   零反推

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!