出于某种原因,我的外部for循环似乎没有做任何事情,我检查了所有的paranthesis,一切看起来还不错,但它仍然没有循环.有了这个程序,我想总计50个随机数(数字可以是1或-1 ......这是计算物理问题)并打印程序所做的大小.但我想进一步做10次,并计算平均幅度.我知道我需要做什么我只是遇到了这个循环的问题.
#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;
}
Run Code Online (Sandbox Code Playgroud)
您不能在两个循环中使用相同的迭代变量.
for(i=0; i<10; i++)
for (i=0; i<50; i++)
Run Code Online (Sandbox Code Playgroud)
递增i到50在外部循环的第一次迭代.
for(i=0; i<10; i++)
for (j=0; j<50; j++)
Run Code Online (Sandbox Code Playgroud)
将工作.
你在i两个循环中使用相同的变量.你应该使用不同的变量.
...
for(j=0; j<10; j++)
{
for (i=0; i<50; i++) //for 50 collisions
{
...
Run Code Online (Sandbox Code Playgroud)