我是 C++ 的初学者,我的一个项目涉及循环内循环和创建随机数。这是我到目前为止所拥有的:`
using namespace std;
int main()
{
srand((unsigned int)time(0));
{
cout << "Name of reservoir: ";
string reservior_name;
cin >> reservior_name;
cout << "Capacity in MAF: ";
double capacity;
cin >> capacity;
cout << "Maximum inflow in MAF: ";
int max;
cin>> max;
cout << "minimum inflow in MAF: ";
int min;
cin >> min;
if(min>max)
{cout<<endl<<"Error: The minimum inflow is higher than the maximum inflow."<<endl
<< "Please re-enter your minimum inflow: ";
cin>>min;
}
double inflow_range= max-min;
cout <<"required outflow in MAF: ";
double required;
cin >> required;
if (required > 0.9 * (min + max)/2)
{
cout<<endl<< "Warning: required ouflow is over 90% of the average inflow."<<endl
<< "Returning to main menu ";
}
else
{ const int simulations = 10;
int water_level = 0;
int years = 1;
cout << "Running simulation..." << endl;
for (int i = 1; i <= simulations; i++)
{
int x = (rand()% (max-min + 1)) + min;
while (water_level < capacity)
{
//double r = rand() * 1.0 / RAND_MAX;
//double x = min + inflow_range * r;
//int x = (rand()% (max-min + 1)) + min;
if (water_level + x > required)
{
water_level = water_level + x - required;
}
else
{
water_level= 0;
}
years++;
}
cout <<"Simulation "<< i <<" took " << years <<" years to finish"<< endl;
}
}
}
system ("pause");
return 0;
}
`
所以我的主要问题是我遇到了关于在“运行模拟”下设置 for 循环的问题,我需要设置第一个 for 循环以运行内部 for 循环 10 次,其中每 10 次迭代内部 for 循环为随机值查询的可接受结果范围提供随机数。有人告诉我这个想法是使用蒙特卡洛方法,即我把蒙特卡洛方法和正常随机数生成方法都放在这里。这里是:
for (int i = 1; i <= simulations; i++)
{
int x = (rand()% (max-min + 1)) + min;
while (water_level < capacity)
{
//double r = rand() * 1.0 / RAND_MAX;
//double x = min + inflow_range * r;
//int x = (rand()% (max-min + 1)) + min;
所以程序将为流入创建一个随机值。这个想法是内部 for 循环将继续运行,直到从 0 开始的水库的 fill_level 达到容量。模拟多少年的过程(内部for循环的每次迭代代表一年)由water_level模拟for循环的父for循环重复10次。
问题是应该创建的随机数是相同的数字。每次我运行它时它们都不同,但每次循环重复以进行新模拟时它们都是相同的。几个小时以来,我一直试图找出问题所在,但仍然卡住了。非常感谢任何帮助。