C语言把固定值随机赋给变量

请问,怎么把几个值随机选一个赋给变量。比如有2,7,9三个数,随机选一个赋给变量a

把你的几个值放在一个数组里,用rand()%N取[0,N-1]之间的随机数,N是你数组的大小,代码如下,如有帮助,请采纳一下,谢谢。

#include <stdio.h>
#include <stdlib.h>
void main()
{
	int arr[5] = {2,3,1,8,9};
	int index = rand()%5;  //取[0-4]之间的随机数

	int a = arr[index];
	index = rand()%5;  //取[0-4]之间的随机数
	int b = arr[index];

	printf("a = %d, b = %d\n",a,b);

	getchar();
	getchar();
}

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(){
    srand((unsigned)time(NULL));

    int a;
    int b = rand()%10;//0-9的随机数
    if(b<3){
       a = 2;
    }else if(b<6){
        a = 7;
    }else{
       a = 9;
    }
    return 0;
}

提供思路如下(C语言):

1、创建一个整型数组存储固定值

2、创建一个最大不超过数组有效下标值大小的随机数

3、每次将产生的随机数作为数组下标去取对应值,然后赋给变量a。

将值存在数组中,再利用rand函数随机选择。