c程序代码在不打印新行的情况下不会停止循环
我有一些c代码,用于列出一个有序int数组的所有排列,然后使用每个排列(目前我只是打印它们),但我注意到,尽管函数按预期工作,但当我删除printf(“\n”);总的来说,程序可以工作,但不会停止。有了它,它工作得很好。代码如下。谁能帮我弄明白发生了什么事c程序代码在不打印新行的情况下不会停止循环,c,C,我有一些c代码,用于列出一个有序int数组的所有排列,然后使用每个排列(目前我只是打印它们),但我注意到,尽管函数按预期工作,但当我删除printf(“\n”);总的来说,程序可以工作,但不会停止。有了它,它工作得很好。代码如下。谁能帮我弄明白发生了什么事 #include <stdio.h> #include <stdlib.h> #define ARRAYSIZE 4 int nextPermutation (int array[], int arraySize);
#include <stdio.h>
#include <stdlib.h>
#define ARRAYSIZE 4
int nextPermutation (int array[], int arraySize);
int main()
{
int *array = calloc(ARRAYSIZE,sizeof(int)),i;
for(i=0; i<ARRAYSIZE; i++)
{
array[i]=i+1;
}
while(nextPermutation(array,ARRAYSIZE))
{
for(i=0; i<ARRAYSIZE; i++)
{
printf("%d ",array[i]);
}
printf("\n");
}
return 0;
}
int nextPermutation(int array[], int arraySize)
{
int maxElement=arraySize,i,maxElementIndex,inDecOrder;
//check to see if the array is in descending order
for(i=0; i<arraySize-1; i++)
{
if(array[i]<array[i+1])
{
inDecOrder = 0;
break;
}
}
//if the array is in descending order then return 0
if(inDecOrder)return 0;
//find the index of the max element.
for(i=0; i<arraySize; i++)
{
if(array[i]==maxElement)
{
maxElementIndex = i;
break;
}
}
if(maxElementIndex!=0)
{
//if the max element is not in the first index then move it left and get next permutation
array[i]=array[i-1];
array[i-1]=maxElement;
return 1;
}
else
{
//if the max index is in the first index then create an array without the max index
int *newArray = calloc(arraySize-1,sizeof(int));
//copy the elements from the first array into the new array with out the max element and get next permutation
for(i=1; i<arraySize; i++)
{
newArray[i-1]=array[i];
}
nextPermutation(newArray,arraySize-1);
for(i=0; i<arraySize-1; i++)
{
array[i]=newArray[i];
}
array[arraySize-1]=maxElement;
return 1;
}
}
#包括
#包括
#定义数组化4
int-nextPermutation(int-array[],int-arraySize);
int main()
{
int*array=calloc(ARRAYSIZE,sizeof(int)),i;
对于(i=0;i),stdio库缓冲输出,仅在输出流中遇到换行符('\n')或显式调用fflush()时才将其写出为实函数。inDecOrder
初始化,如int inDecOrder=1;
@WhozCraig,我应该启用设置中的所有编译器警告吗?当然,至少是我在链接示例中显示的那些警告。工具链在如何执行方面有所不同,但总是这样做。警告几乎总是表示程序至少存在逻辑错误。They应该被修复;而不是被忽略。按照@BLUEPIXY告诉我的方法修复了我的问题。谢谢。