C语言 利用洗牌将字符串随机打乱10次
课程设计
1
如果需要将下面的代码给改成,用户自己输入字符串,并且字符数不能少于5个,否则输出“String length must at least be 5. Please try again.”当输入长度为5或者以上的字符串时,将字符串洗牌shuffle10次
#include <stdio.h>
void shuffle(int array[], int size) {
for(int i = 0; i < size; i++) {
int j = rand()%size;
int t = array[i];
array[i] = array[j];
array[j] = t;
}
}
int main(void){
int list[10] = {0,1,2,3,4,5,6,7,8,9};
shuffle(list, 10);
for (int i = 0; i < 10; i++) {
printf("%d,", list[i]);
}
return 0;
}
-
修改如下
#include <stdio.h> #include <string.h> void shuffle(char array[], int size) { int i; for( i = 0; i < size; i++) { int j = rand()%size; char t = array[i]; array[i] = array[j]; array[j] = t; } } int main(){ char list[5]={1}; int flg=1; printf("Enter a string of length 5:\n"); while(flg==1) { gets(list); int len=strlen(list); if(strlen(list)<5) { printf("String length must at least be 5. Please try again.\n"); printf("Enter a string of length 5:\n"); flg=1; } else { flg++; int i,j; for(j=0;j<10;j++) { printf("Shuffle %d: ",j+1); shuffle(list,len); for ( i = 0; i < len; i++) { printf("%c", list[i]); } printf("\n"); } } } return 0; }
-
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> void shuffle(char *s,int n) { int i,j; char t; for(i = 0; i < 10; i++) { j = rand()%n; t = s[i%n]; s[i%n] = s[j]; s[j] = t; printf("Shuffle %d: %s\n",i+1,s); } } int main(void){ char s[100]; printf("Enter a string of length 5:\n"); gets(s); while(strlen(s) < 5) { printf("String length must at least be 5. Please try again.\n"); printf("Enter a string of length 5:\n"); gets(s); } srand(time(NULL)); shuffle(s, strlen(s)); return 0; }
发表回复