我正在尝试编写一个C++程序,用非重复的字母从a-z(ascii代码97到122)打印一个随机的10个字母的字符串。我写过这段代码,有时可以完美运行,但while循环无限运行的大部分时间。 问题在哪里?如何打印非重复字母的随机字符串?
(编辑:在同时开始设置标志= 0解决了这个问题)
void randomstring()
{int i,j,flag=1;
char x, s[20]=" ";
srand(time(0));
for(i=0;i<10;i++)
{flag=1; //ensure entry into while
while(flag)
{x=rand()%26+97; //get random letter from a-z
for(j=0;j<10;j++)
{if(x==s[j]) //match with existing letters
flag=2; //if matched, try again
}
if(flag!=2)
{s[i]=x; //if doesn't match, add to string
flag=0; //exit while
}
}
}
cout<<s;
}
[可能的重复](http://stackoverflow.com/questions/41015311/picking-about-random-character-without-repetition-c) – izlin
使用循序渐进的调试 –