我对使用数组有点新意,所以我会尽力评论我所知道的代码的哪些部分,然后我希望你能帮助我解释并澄清其余部分。目标是获得10个元素(数字)然后按顺序排序(从最大到最小,反之亦然)
#include <stdio.h>
#include <stdlib.h>
void input();
void sort();
int array[10];
int main()
{
char ans='y';
while(ans=='y'||ans=='Y') /// Run the program while 'y' is entered
{
input(); // run the input function
sort(); // run the sort function
printf("\n Run Program Again?"); // ask user for input (char ans)
scanf("%s",&ans);
}
}
void input()
{
int x;
for (x = 0; x < 10 ; x++)
{ //This is where I get confused. If my int x is =0, less than 10, I don't know what "++ means
printf("\nInput: "); //ask for input
scanf("%d", &array[x]); //get the input typed in and place in array x
}
}
void sort()
{
{
int x = 0;
int y = 0;
int z = 0;
int biggerNum = 0;
int smallerNum = 0; //set values for integers
for (z = 10; z > 0; z--) { // can someone explain this part?
for (x = 0; x <= 10; x++) {
if (array[z] < array[x])
continue;
else {
biggerNum = array[z];
smallerNum= array[x];
array[z] = smallerNum;
array[x] = biggerNum;
printf("\n%d\t%d",array[z],array[x]);
}
}
}
printf("\nDescending order:");
for (x = 0; x < 10; x++) // this is the algorithm for going down
printf("\n %d",array[x]);
printf("\nAscending Order:"); // same for going up
for (x = 10; x > 0; x--)
printf("\n %d",array[x]);
}
}
答案 0 :(得分:1)
我正在描述。我认为这对你有所帮助。
第一部分:
char ans='y';
while(ans=='y'||ans=='Y') /// Run the program while 'y' is entered
{
input(); // run the input function
sort(); // run the sort function
printf("\n Run Program Again?"); // ask user for input (char ans)
scanf("%s",&ans);
}
首先,您按ans
初始化'y'
(它是一种字符数据类型)。因此,它将进入while
循环。然后通过input()
函数获取10个数字。然后通过sort()
函数,您将这10个数字从最大到最低排序,反之亦然。然后再次输入ans
。如果您(用户)再次访问'y'
或'Y'
,则会继续。否则while
循环将中断,程序将终止。
第二部分:
void input()
{
int x;
for (x = 0; x < 10 ; x++)
{
//This is where I get confused. If my int x is =0, less than 10, I dont
//know what "++ means
printf("\nInput: "); //ask for input
scanf("%d", &array[x]); //get the input typed in and place in array x
}
}
此代码实际上用于获取10个数字。这里&#39; x++
&#39;表示x
的增量。这意味着x=x+1
。您按scanf
将这10个数字存储在数组中。
第三部分:
void sort()
{
{
int x = 0;
int y = 0;
int z = 0;
int biggerNum = 0;
int smallerNum = 0; //set values for integers
for (z = 10; z > 0; z--) // can someone explain this part?
{
for (x = 0; x <= 10; x++)
{
if (array[z] < array[x])
continue;
else
{
biggerNum = array[z];
smallerNum= array[x];
array[z] = smallerNum;
array[x] = biggerNum;
printf("\n%d\t%d",array[z],array[x]);
}
}
}
printf("\nDescending order:");
for (x = 0; x < 10; x++) // this is the algorithm for going down
printf("\n %d",array[x]);
printf("\nAscending Order:"); // same for going up
for (x = 10; x > 0; x--)
printf("\n %d",array[x]);
}
它是10个数字的分类。实际上它被称为bubble sort。