C 程序返回n个元素的所有排列?无限循环?
此代码应输出n个元素的所有排列,因此当我输入示例3 output时,它必须:C 程序返回n个元素的所有排列?无限循环?,c,algorithm,C,Algorithm,此代码应输出n个元素的所有排列,因此当我输入示例3 output时,它必须: ABC 美国银行 驾驶室 ACB BCA CBA 使用此代码: #include <stdio.h> #include <string.h> void swap(char *x, char *y){ char temp; temp = *x; *x = *y; *y = temp; } void permute(char *a, int l, int r){ int i;
ABC
美国银行
驾驶室
ACB
BCA
CBA
使用此代码:
#include <stdio.h>
#include <string.h>
void swap(char *x, char *y){
char temp;
temp = *x;
*x = *y;
*y = temp;
}
void permute(char *a, int l, int r){
int i;
if (l == r)
printf("%s\n", a);
else
{
for (i = l; i <= r; i++){
swap((a+l), (a+i));
permute(a, l+1, r);
swap((a+l), (a+i));
}
}
}
int main(){
int x , n ;
int i = 0 ;
char str[26];
printf("prem ");
scanf("%d",&x);
while (x > 0){
str[i] = 'A' + i ;
i++;
x--;
}
n = strlen(str);
permute(str, 0, n-1);
}
#包括
#包括
无效交换(字符*x,字符*y){
焦炭温度;
温度=*x;
*x=*y;
*y=温度;
}
无效排列(字符*a,整数l,整数r){
int i;
如果(l==r)
printf(“%s\n”,a);
其他的
{
对于(i=l;i 0){
str[i]=“A”+i;
i++;
x--;
}
n=strlen(str);
排列(str,0,n-1);
}
我应该为一个数字键入我想要的,例如ABC为3,ABC为4,然后代码应该处理这个问题,但它不起作用,而是在一个无限循环中运行
但对于此代码:
#include <stdio.h>
#include <string.h>
void swap(char *x, char *y){
char temp;
temp = *x;
*x = *y;
*y = temp;
}
void permute(char *a, int l, int r){
int i;
if (l == r)
printf("%s\n", a);
else
{
for (i = l; i <= r; i++){
swap((a+l), (a+i));
permute(a, l+1, r);
swap((a+l), (a+i));
}
}
}
int main()
{
char str[26];
gets(str);
int n = strlen(str);
permute(str, 0, n-1);
return 0;
}
#包括
#包括
无效交换(字符*x,字符*y){
焦炭温度;
温度=*x;
*x=*y;
*y=温度;
}
无效排列(字符*a,整数l,整数r){
int i;
如果(l==r)
printf(“%s\n”,a);
其他的
{
对于(i=l;i而言,您的main应该是:
int main(){
int x , n ;
int i = 0 ;
char str[26];
printf("prem ");
scanf("%d",&x);
//user entered the string length in x, let' save it in n
n = x;
while (x > 0){
str[i] = 'A' + i ;
i++;
x--;
}
//n = strlen(str); ===> this is wrong, the user did not entered a string
permute(str, 0, n-1);
}
在工作代码(您发布的第二块代码)中,用户输入一个字符串,该字符串存储在str
变量中:
gets(str);
然后使用strlen
将字符串长度传递给permute
函数:
int n = strlen(str);
permute(str, 0, n-1);
在第一个(非工作)代码块中,您要求用户输入长度,而不是字符串,并将其存储在x
中。然后将x
字符放入str
数组中,但这不是正确的c字符串,因为缺少空终止符。因此strlen
返回值非常不可靠
如果你不喜欢我建议的解决方案,你可以提供一个
str[i] = '\0';
就在while
阻塞并保持其他所有内容不变之后,它仍然可以工作。问题是strlen
是在未终止的字符串上调用的
在字符串末尾添加'\0'
,以终止该字符串:
while (x > 0){
str[i] = 'A' + i ;
i++;
x--;
}
str[i] = '\0';
或(更好)
使用x
的原始值调用permute
(在scanf
之后保存它)。问题是str字符串没有正确终止,因此n=strlen(str);
的结果未定义。strlen
对字符进行计数,直到遇到\0
int main(){
int x , n ;
int i = 0 ;
char str[26];
printf("prem ");
scanf("%d",&x);
while (x > 0){
str[i] = 'A' + i ;
i++;
x--;
}
str[i] = 0; // terminate the string
n = strlen(str);
permute(str, 0, n-1);
}