我如何在C ++ / C中分配随机变量?

问题描述 投票:-4回答:3

我以前从未做过(随机化)。但是,如何在3个整数之间随机分配。界线之间的东西。我是C ++或C语言编程的新手。我使用C,但C ++答案也可以使用; P

int main (void){

int; a
int; b
int; c

rand(?) %?; 

if(a){
printf(its A!);
}
if(b){
printf(ITS B!);
}
else
printf(its C!);
 }
}
c++ c
3个回答
2
投票
#include <random>
#include <iostream>

int main()
{
  int var[3] = {1, 2, 3};

  std::random_device device;
  std::mt19937 prng(device());
  std::uniform_int_distribution<std::mt19937::result_type> distribution(0, 2);

  std::cout << var[distribution(prng)] << std::endl;

  return 0;
}

对于单独的变量:

#include <random>
#include <iostream>
int main()
{
  int a = 1;
  int b = 2;
  int c = 3;

  std::random_device device;
  std::mt19937 prng(device());
  std::uniform_int_distribution<std::mt19937::result_type> distribution(0, 2);

  switch (distribution(prng))
  {
    case 0: std::cout << "a = " << a << std::endl; break;
    case 1: std::cout << "b = " << b << std::endl; break;
    case 2: std::cout << "c = " << c << std::endl; break;
  }

  return 0;
}

1
投票

如果您能够使用array,那么这将非常容易地消失:

int a[] = {1, 2, 3};
int random = a[rand() % 3]; // random is an element of a

((如果需要将变量分开,则可以使用指向这些变量的指针数组。)


0
投票

您可以尝试以下方法

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

int main(){
    int i, a,b,c;
    srand (time(NULL));
    i = rand() % 3;

    if (i==0){
        printf("Its A!");
    }else if (i==1){
        printf("Its B!");
    }else if (i==2){
        printf("Its C!");
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.