在这个问题上我得到了排序(a,4),排序(a,6)。
Starting with sort(a,4)
npts =4 which mean I need to loop from 0 ~ 2
1st loop x[] = { 5,7,3,1,6,9}
2nd loop x[] = {5,3,7,1,6,9}
3rd loop x[] = {5,3,1,7,6,9}
exit the loop
counter =1;
back into the for loop
1st loop x[] = {3,5,1,7,6,9}
2nd loop x[] = {3,1,5,7,6,9}
exit loop the loop
counter =2;
back into the for loop
1st loop x[] = {1,3,5,7,6,9}
exit the loop
counter =3;
back into the for loop
but exit immediately since 1>3
counter = 4;
Then going to the sort(a,6);
counter =1 since 1>3;
But the answer is opposite when I compile using mingw which is 1 4
我的代码如下:
#include <stdio.h>
int sort (int x[],int npts);
int main(void)
{
int a[] = {7,5,3,1,6,9};
printf("%d %d\n",sort(a,4),sort(a,6));
return 0;
}
int sort(int x[] , int npts)
{
int counter =0, done, hold ,k;
do
{
done =1;
for(k=0;k<=npts-2;k++)
{
if (x[k] > x[k+1])
{
hold= x[k];
x[k] = x[k+1];
x[k+1] = hold;
done =0;
}
}
counter++;
}while (!done);
return counter;
}
最佳答案
Starting with sort(a,4) npts =4 ...
不,不一定。您似乎希望先调用
sort(a,4)
,然后再调用sort,6)
。printf()函数参数的求值顺序未指定。这意味着,您不知道sort(1,4
和sort(a,6)
中的哪个将首先被调用。一个接一个地打电话给他们会得到可预见的结果。
关于c - 我可以知道为什么此代码的计数器是1和4吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27075757/