【发布时间】:2015-03-02 00:22:13
【问题描述】:
我试图制作一个细菌模型只是为了好玩,我正在使用 pow(a, b) 函数作为计算人口增长的函数。当细菌种群达到其环境所能提供的最大食物单位数量时,由于个体之间的竞争,它会下降 70%。我将结果保存到 txt,以便稍后绘制。我遇到的问题是种群正确振荡,直到我达到 t = 900 附近的多个繁殖周期,然后种群默认为 0。 代码如下,希望你不要介意葡萄牙语写的变量和函数的名称。
bool
check_aliemento (unsigned long int *pop)
{
if (*pop >= MAX_ALIMENTO) return false;
return true;
}
unsigned long int
replicaBacteria (unsigned long int *popInit, unsigned int tempo_t, double taxa)
{
unsigned long int nextPop = round ((*popInit) *
static_cast<double> (pow (1 + taxa, tempo_t)));
//I'm almost sure that the problem happens in this pow() function
while (! check_aliemento (&nextPop))
{
nextPop = (0.7 * nextPop);
}
return nextPop;
}
int
main ( int argc, char** argv )
{
unsigned long int a = 2;
ofstream myfile;
myfile.open ( "C:\\Users\\Pedro\\Desktop\\values.txt" );
for ( unsigned int i; i < 1000; i ++ )
{
unsigned long int pop = replicaBacteria ( &a, i, 0.05 );
myfile << pop << " ==> time = " << i;
myfile << "\r\n";
}
myfile.close ( );
return 0;
}
示例输出:
8080 ==> time = 872
8484 ==> time = 873
8909 ==> time = 874
9354 ==> time = 875
9822 ==> time = 876
7219 ==> time = 877
7580 ==> time = 878
7958 ==> time = 879
8357 ==> time = 880
8775 ==> time = 881
9214 ==> time = 882
9675 ==> time = 883
7110 ==> time = 884
7466 ==> time = 885
7839 ==> time = 886
8232 ==> time = 887
8643 ==> time = 888
9075 ==> time = 889
9529 ==> time = 890
7003 ==> time = 891
7354 ==> time = 892
7721 ==> time = 893
8108 ==> time = 894
8513 ==> time = 895
0 ==> time = 896
0 ==> time = 897
0 ==> time = 898
0 ==> time = 899
0 ==> time = 900
【问题讨论】:
-
更改您的
data type int to long long可能是由于 Population 增加太多,因此无法存储在 int 中。 -
我已经确保在这种情况下,人口不会超过 10000,这完全适合 int。
-
i 的初始值是多少?
-
编译器自动设置为0。gcc之美!
-
是的,你的 nextPop 有问题,通过打印检查它的值。