gpt4 book ai didi

c - 我的冒泡排序出了什么问题?

转载 作者:行者123 更新时间:2023-11-30 21:39:07 26 4
gpt4 key购买 nike

此代码使用 9 个值(电影名称)初始化一个指针数组,然后鼓励用户输入每部电影的评级。输入每部电影的评级后,冒泡排序代码应该将每部电影从最低到最高排序。最后,电影列表应该按照从低到高的顺序打印出来。不幸的是,用于按评级顺序打印电影的代码的最后一部分不起作用。这是为什么?

int i;
int ctr = 0;
char ans;
char * movies[9] = {"Amour", "Argo","Beasts of the Southern Wild","Django Unchained","Les Miserables","Life of Pi", "Lincoln","Silver Linings Playbook","Zero Dark Thirty"};
int movieratings[9];
char *tempmovie ;
int didSwap, temprating;

printf("\n\n*** Oscar Season 2012 is here and the nominees are: ***\n\n");

for (i=0;i<9;i++)//FOR LOOP TO PRINT OUT VALUES IN movies
{
printf(" %s\n",movies[i]);
}
printf("Time to rate this year's best picture nominees:");

for (i=0; i< 9; i++)//for loop to rate movies
{
printf("\nDid you see %s? (Y/N): ", movies[i]);
scanf(" %c", &ans);

if ((toupper(ans)) == 'Y')

{
printf("\nWhat was your rating on a scale of 1-10:");
scanf(" %d", &movieratings[i]);
ctr++;//counter to recognise how many movies you have seen
continue;
}

else
{
movieratings[i] = -1;
}
}

// Now sort the movies by rating (the unseen will go
// to the bottom)

while(1)//bubble sort to sort movies by rating
{
didSwap = 0;
for (i = 0; i < 9; i++)
{
if (movieratings[i] > movieratings[i+1])
{
tempmovie = movies[i];
temprating = movieratings[i];
movies[i] = movies[i+1];
movieratings[i] = movieratings[i+1];
movies[i+1] = tempmovie;
movieratings[i+1] = temprating;
didSwap = 1;
}
}
if (didSwap == 0)
{
break;
}
}


printf("\n\n** Your Movie Ratings for the 2012 Oscar Contenders **\n");

for (i=0; i<ctr; i++)
{
printf("%s rated a %d \n", movies[i], movieratings[i]);
}

最佳答案

您正在对 movieratings 进行排序按升序排列数组并打印 ctr元素从头开始,因此它会打印评级最低的电影。按降序对数组进行排序,即更改此 if (movieratings[i] > movieratings[i+1])if (movieratings[i] < movieratings[i+1])

关于c - 我的冒泡排序出了什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40198854/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com