我正在使用rand()生成一个随机数,并将其显示在算术问题的上下文中。我每次都得到相同的两个数字。我每次如何使它们不同?
#include <iostream>
#include<cstdlib>
using namespace std;
int main()
{
int numberOne = rand()%1000;
int numberTwo = rand()%1000;
int numberThree = numberOne + numberTwo;
char input;
cout << " " << numberOne << endl;
cout << "+" << numberTwo << endl;
cout << "----";
cin.get();
cout << numberThree << endl;
}
答案 0 :(得分:1)
#include <iostream>
#include<cstdlib>
using namespace std;
int main()
{
/* initialize random seed: */
srand (time(NULL));
int numberOne = rand()%1000;
int numberTwo = rand()%1000;
int numberThree = numberOne + numberTwo;
char input;
cout << " " << numberOne << endl;
cout << "+" << numberTwo << endl;
cout << "----";
cin.get();
cout << numberThree << endl;
}
为了获得随机数,您需要提供一个种子。