每当我运行此代码时,我都会得到相同的结果.
程序
#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++新手,我很难过.我需要在我的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) 为什么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)