相关疑难解决方法(0)

为什么每次编译和运行时都会使用rand()获得相同的结果?

每当我运行此代码时,我都会得到相同的结果.

程序

#include<stdlib.h>

int main(int agrc, const char *argv[]) {
 int i = rand();
 printf("%d\n",i);
 for(i=0;i<10;i++) {
  printf("%d\n",rand());
 }
}
Run Code Online (Sandbox Code Playgroud)

结果:

41
18467
6334
26500
19169
15724
11478
29358
26962
24464
5705
Run Code Online (Sandbox Code Playgroud)

我跑了这个mingw.其实我在学习Objective-C

请帮我.

c random

7
推荐指数
2
解决办法
2万
查看次数

在单个函数中调用时,rand()返回相同的值

我是一个C++新手,我很难过.我需要在我的main函数中调用这个函数三次,但每次它给我相同的结果,即pull_1,pull_2,pull_3是相同的.我需要做些什么来使它们实际上是随机的?

string PullOne()
{
    string pick;
    string choices[3] = {"BAR", "7", "cherries"};

    std::srand(time(0));
    pick = choices[(std::rand() % 3)];
    return pick;
}
Run Code Online (Sandbox Code Playgroud)

从我的主要功能:

string pull_1, pull_2, pull_3;
pull_1 = PullOne();
pull_2 = PullOne();
pull_3 = PullOne();
Run Code Online (Sandbox Code Playgroud)

c++ random

6
推荐指数
3
解决办法
5917
查看次数

rand()生成相同的数字

可能重复:
当在单个函数c ++中调用时,rand函数返回相同的值

为什么rand()生成相同的数字?

die.h

#ifndef DIE_H
#define DIE_H


class Die
{
private:
    int number;
public:
    Die(){number=0;}
    void roll();
    int getNumber()const{return number;}
    void printValue();
};

#endif
Run Code Online (Sandbox Code Playgroud)

die.cpp

#include"die.h"
#include<iostream>
#include<time.h>
using namespace std;

void Die::roll()
{
    srand(static_cast<int>(time(0)));
    number=1+rand()%6;
}

void Die::printValue()
{
    cout<<number<<endl;
}
Run Code Online (Sandbox Code Playgroud)

main.cpp中

#include"die.h"
#include<iostream>
using namespace std;

int main()
{
    Die d;
    d.roll();
    d.printValue();
    d.roll();
    d.printValue();
    d.roll();
    d.printValue();
}
Run Code Online (Sandbox Code Playgroud)

c++ visual-c++

1
推荐指数
1
解决办法
5131
查看次数

标签 统计

c++ ×2

random ×2

c ×1

visual-c++ ×1