2011-11-09 80 views
-1

出於某種原因,我的外循環似乎並沒有做任何事情,我已經檢查了所有palenthesis,一切都看起來不錯,但它仍然沒有循環。 有了這個程序,我想總結50個隨機數(數字可以是1或-1 ...這是一個計算物理問題),並打印程序的大小。但我想進一步做這10次,並計算平均幅度。 我知道我需要做什麼我只是有這個循環的問題。for循環for循環內c

#include<stdio.h> 
#include<math.h> 
#include<stdlib.h> 
#include<time.h> //Neeed this to seed the random generator with time, or else it  will always generate the same numbers. 

//This is a program to calculate the magnitude of the displacement of a particle after random collisions. 
#define RAND_MAX 1 
int main() 
{ 
    //using ints because the particle can only move one unit on x-axis at a time. 
    int i, x, displacement, sum = 0, avg; 
    int total_disp=0, mag_disp; 
    srand(time(NULL)); 


    //Each collision causes the particle to advance or retreat by one unit on the x axis. 

    for(i=0; i<10; i++) 
    { 
     for (i=0; i<50; i++) //for 50 collisions 
     { 

      x = rand() % 2; //generates random numbers between 0 and 1. 
      if (x==0) //if x is 0 then it was a displacement in the minus x direction 
      { 
       displacement = -1; 
      } 
      else { //if x is 1 it is a displacement in the minus x direction 
       displacement = 1; 
      } 
      printf("the disp is : %d\n", displacement); 
      total_disp = total_disp + displacement;  //sum the displacements 

     } 

     if (total_disp < 0) { 
      mag_disp = total_disp * -1; 
     } 

     else{ mag_disp = total_disp; } 

     printf("The total displacement is: %d\n", mag_disp); 
     sum = sum + mag_disp; //sum of the displacement magnitudes, there should be ten of them in this case 
     avg = sum/i; //average displacement is the sum of all the magnitudes divded by the number of times this is performed. 
     printf("The average displacement for i = %d particles is: %d", i, avg); 
    } 
    return 0; 
} 
+0

你不能重新定義'RAND_MAX'。 –

+0

在內循環開始之前,您應該在外循環內設置total_disp爲0。如果你將不同的事情分離到不同的功能中,這個錯誤和關於在兩個循環中使用相同變量的錯誤都會被避免。 –

回答

6

您無法在兩個循環中使用相同的迭代變量。

for(i=0; i<10; i++) 
    for (i=0; i<50; i++) 

i增量在外部循環的第一次迭代50

for(i=0; i<10; i++) 
    for (j=0; j<50; j++) 

將工作。

3

對內部和外部循環使用不同的循環變量。

當內循環的第一次迭代完成時i == 50,所以外循環也完成了。

+0

更正:i = 51 – slebetman

+0

不,上一次輸入循環,i == 49。然後我增加1,循環測試'我<50'失敗。 – Mat

5

對兩個循環使用相同的變量i。你應該使用不同的變量。

... 
for(j=0; j<10; j++) 
{  
    for (i=0; i<50; i++) //for 50 collisions 
    { 
    ... 
1

試試這個:

for(int i=0; i<10; i++) 
{ 
    for(int j=0; j<50; j++) 
    { ... } 
} 

並相應地改變你的變量。

+1

毫無意義的事實:如果你喜歡這個,並且在for循環中聲明瞭迭代器,它可能會爲變量'i'命名。每當從最內層循環訪問「我」時,它都會提到最內層的「我」。但是......不要將它們命名爲相同的東西,它只會使代碼難以閱讀。 – Lundin

+1

這不是'C'。 – Dennis

0

丹尼斯是對的。

在ANSI C

,i和j必須在函數的開頭聲明:

int main() 
{ 
int i,j; 

...//instructions 

for(i=0; i<10; i++) 
{ 
    for(j=0; j<50; j++) 
    { ... } 
}