如何在c ++中执行随机结果作为下面的代码? [英] How can I execute random results in c++ as the code given below?

查看:136
本文介绍了如何在c ++中执行随机结果作为下面的代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 #include <iostream>
 using namespace std;
 int main(){
     int results[] = {1, 2, 3, 4, 5};
     cout << results << endl;
     return 0;
 }



每次我想要不同
例如:第一次1秒时间2等
任何帮助?

I want different result each time. for example: first time 1 second time 2 etc. Any help?

推荐答案

是用当前时间为基本随机数生成器种子,然后使用 rand() reduced modulo从结果中选择随机元素的可能结果的数量

One easy way is to seed the basic random number generator with the current time then use rand() reduced modulo the number of possible results to choose a random element from results

#include "iostream"
#include <cstdlib>
#include <ctime>
using namespace std;
int main(){
    int results[] = {1, 2, 3, 4, 5};
    srand(time(NULL));
    cout << results[rand()%(sizeof(results)/sizeof(results[0]))] << endl;
    return 0;
}

这篇关于如何在c ++中执行随机结果作为下面的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆