0
我似乎無法弄清楚我的問題是什麼。我正在編寫一個2D隨機遊走模擬,我的想法是使用二維數組來模擬它所在的網格。然而,在我的代碼中,當我嘗試引用數組中的特定單元格來增加它的值時,比如說bin [3] [4],它會增加整個索引的值,即bin [1] [4],bin [ 2] [4],倉[3] [4],等等。任何想法如何解決這個問題或我做錯了什麼?謝謝。二維數組引用整個索引,而不是C中的單個單元格
#include <stdio.h>
#include <math.h>
#define total 10. /*total iterations*/
#define walk 5 /*total # of steps in a walk*/
#define lambda 1.0 /*step size*/
#define binsize 0.1
/*current chosen values are for bug checking simplicity*/
main()
{
float range = walk*lambda*2.; /*2 times max range, all positive*/
int n,prob,i,k,j,placex,placey,bins;
double valuex,valuey, a; /*value starts at half range so all values are +*/
bins=(range/binsize);
int bin[bins][bins];
for(i=0;i<=bins;i++) /*zero out bin*/
{
for(j=0;j<=bins;j++)
{
bin[i][j]=0;
}
}
for(k=0;k<total;k++)
{
valuex=range/2.;
valuey=range/2.;
for(n=1;n<=walk;n++)
{
prob= rand(4) % 100+1;
if(prob<=25)
{
valuex=valuex+pow(lambda,n);
}
else if(prob>25 && prob<=50)
{
valuex=valuex-pow(lambda,n);
}
else if(prob>50 && prob<=75)
{
valuey=valuey+pow(lambda,n);
}
else if(prob>75)
{
valuey=valuey-pow(lambda,n);
}
}
placex=floor(valuex/binsize+0.5);
placey=floor(valuey/binsize+0.5);
bin[placex][placey]=++bin[placex][placey];
printf("%d %d %d\n",placex,placey,bin[placex][placey]); /* for bug checking. it prints the bin numbers where the value should go and then the value of that element.*/
}
for(i=0;i<=bins;i++)
{
for(j=0;j<=bins;j++)
{
a=bin[i][j]/total;
//printf("%lf %lf %lf\n",i*binsize-range/2.,j*binsize-range/2.,a); /*format for input into IGOR*/
}
}
}
行'bin [placex] [placey] = ++ bin [placex] [placey];'給出未定義的結果,您可能的意思是:'bin [placex] [placey] ++;' – Kninnug
Kninnug,謝謝!我曾經把它當作bin [placex] [placey] = bin [placex] [placey] +1;我認爲改變它可能會解決我的問題,但事實並非如此。 – keduong