出於某種原因,我的外循環似乎並沒有做任何事情,我已經檢查了所有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;
}
你不能重新定義'RAND_MAX'。 –
在內循環開始之前,您應該在外循環內設置total_disp爲0。如果你將不同的事情分離到不同的功能中,這個錯誤和關於在兩個循環中使用相同變量的錯誤都會被避免。 –