C ++随机int函数 [英] C++ random int function

查看:121
本文介绍了C ++随机int函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好亲爱的stackoverflow成员我最近开始学习C ++,今天我写了一个小游戏,但我的随机函数不能正常工作。当我调用我的随机函数多次,它不会重新生成一个数字,它打印了相同的数字一遍又一遍。如何在不使用for循环的情况下解决这个问题?
感谢

Hello dear members of stackoverflow I've recently started learning C++, today I wrote a little game but my random function doesn't work properly. When I call my random function more than once it doesn't re-generate a number instead, it prints the same number over and over again. How can I solve this problem without using for loop? Thanks

#include "stdafx.h"
#include <iostream>
#include <time.h>
using namespace std;
int rolld6();

int main()
{
    cout<<rolld6()<<endl;
    cout<<rolld6()<<endl;
    system("PAUSE");
    return 0;

}

int rolld6()
{
    srand(time(NULL));
    return rand() % 6 + 1;;
}


推荐答案

srand(time(NULL)); 通常应在 main()开始时 。

srand(time(NULL)); should usually be done once at the start of main() and never again.

每次你在同一秒钟调用 rolld6 时,你的方法会给你相同的数字,可以是很多次,在您的示例中,接近保证,因为您连续两次调用它。

The way you have it will give you the same number every time you call rolld6 in the same second, which could be a lot of times and, in your sample, is near guaranteed since you call it twice in quick succession.

尝试这样:

#include "stdafx.h"
#include <iostream>
#include <time.h>
#include <stdlib.h>

int rolld6 (void) {
    return rand() % 6 + 1;
}

int main (void) {
    srand (time (NULL));
    std::cout << rolld6() << std::endl;
    std::cout << rolld6() << std::endl;
    system ("PAUSE");
    return 0;
}

另一件事要记住的是,如果你运行这个程序本身两次快速继承。如果时间没有改变,你将在两次运行中得到相同的两个数字。这通常是一个问题,当你有一个脚本多次运行程序和程序本身是短暂的。

One other thing to keep in mind is if you run this program itself twice in quick succession. If the time hasn't changed, you'll get the same two numbers in both runs. That's only usually a problem when you have a script running the program multiple times and the program itself is short lived.

例如,如果你拿出你的 system()调用并且有一个 cmd.exe 脚本,它叫三次,你可能会看到:

For example, if you took out your system() call and had a cmd.exe script which called it thrice, you might see something like:

1
5
1
5
1
5

这不是你通常做的事情,但应该记住场景弹出的机会。

It's not something you usually do but it should be kept in mind on the off chance that the scenario pops up.

这篇关于C ++随机int函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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