我正在制作一个琐事游戏,并在函数中有问题来获取随机问题我试图选择一个0,1或2的随机整数。根据我得到的东西,我将指向一个函数并运行该函数。我想这样做,当我再次这样做时,我可以确保我不再得到这个整数,以便不运行相同的问题。
这就是我现在拥有的
srand(time(NULL));
int randomnumber;
randomnumber = rand() % 3;
但它只是得到一个介于0和2之间的随机整数,然后不让我选择三个直接整数,然后在运行时将它们从这个数组中取出。
对于少量项目,请使用无效值替换所选项目。 可以使用开关来处理随机项。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int main( void) {
char items[] = "012";
int each = 0;
srand ( time ( NULL));
while ( 1) {
if ( ! strcmp ( " ", items)) {
printf ( "all items used\n");
break;
}
do {//find an item that is not ' '
each = rand ( ) % 3;
} while ( items[each] == ' ');
switch ( items[each]) {
case '0':
printf ( "using item 0\n");
//do other things here as needed
break;
case '1':
printf ( "using item 1\n");
//do other things here as needed
break;
case '2':
printf ( "using item 2\n");
//do other things here as needed
break;
}
items[each] = ' ';//set used item to ' '
}
return 0;
}
有很多方法可供选择。其中一个是创建一个整数数组,在你的情况下,它的大小为3,数字为0 ... 2。现在洗牌这个数组。有很多算法可以做到这一点。一个例子是this。 现在,只需遍历这个新创建的shuffle数组来调用函数。在这种情况下,您的要求都将得到满足。问题将按随机顺序排列,您不会再次拨打相同的号码。 此代码示例将帮助您入门:
void shuffle ( int arr[], int n ) {
srand ( time(NULL) );
//this will shuffle the array
for (int i = n-1; i > 0; i--){
// Pick a random index from 0 to i-1
int j = rand() % (i);
// Swap arr[i] with the element at random index
swap(&arr[i], &arr[j]);
}
}
int main(){
int arr[] = {0, 1, 2};
shuffle(arr, 3);
int i;
for(i = 0; i < 3; i++){
// call the function with shuffled array
}
}
您需要编写交换功能。