一个C语言全排列问题

来源:百度知道 编辑:UC知道 时间:2024/09/25 05:30:14
#include "stdafx.h"
#include <stdio.h>

int used[30],p[30],n;

void go(int k)
{
int i;
if(k==n)
{
for(i=0;i<n;i++)printf("%d",p[i]+1);
printf("\n");
return;
}
for(i=0;i<n;i++)
{
if(used[i])continue;
used[i]=1;
p[k]=i;
go(k+1);
used[i]=0;
}
}

int main()
{
printf("Input number:");
while(scanf("%d",&n)==1)
{
go(0);
printf("Input number:");
}
}
这个程序main里没有写到进入函数go,为什么它会进入go,打出全排列?
这句while(scanf("%d",&n)==1) 是不

楼主认为没有进入函数go,可能是对scanf()函数返回值了解不够准确
关于scanf的返回值,MSDN里是这样写的:
Both scanf and wscanf return the number of fields successfully converted
and assigned; the return value does not include fields that were read but
not assigned. A return value of 0 indicates that no fields were assigned.
The return value is EOF for an error or if the end-of-file character or the
end-of-string character is nocountered in the first attempt to read a character.
如:

scanf("%d%d", &a, &b);
如果a和b都被成功读入,那么scanf的返回值就是2
如果只有a被成功读入,返回值为1
如果a和b都未被成功读入,返回值为0
如果遇到错误或遇到end of file,返回值为EOF。

所以这里while的条件是while(scanf("%d",&n)==1) ,意思是成功输入一个n就进入循环,也就调用了go函数。

不知道这样解释,楼主满意否?

int main()
{
printf("Input number:");
while(scanf("%d",&n)==1)
{
go(0); //函数调用go
printf("Input number:");
}
}

int main()
{
printf("Input number:&