Цикл For в цикле For в C - PullRequest
       11

Цикл For в цикле For в C

0 голосов
/ 09 ноября 2011

По какой-то причине мой внешний цикл for, похоже, ничего не делает, я проверил весь парантез, и все выглядит нормально, но он все еще не зацикливается. С помощью этой программы я хочу суммировать 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;
}

Ответы [ 5 ]

6 голосов
/ 09 ноября 2011

Нельзя использовать одну и ту же переменную итерации в обоих циклах.

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++)

будет работать.

5 голосов
/ 09 ноября 2011

Вы используете одну и ту же переменную i для обоих циклов.Вы должны использовать разные переменные.

...
for(j=0; j<10; j++)
{    
   for (i=0; i<50; i++)    //for 50 collisions
   {
    ...
3 голосов
/ 09 ноября 2011

Используйте разные переменные цикла для внутреннего и внешнего цикла.

Когда первая итерация внутреннего цикла выполнена i == 50, значит, внешний цикл также выполнен.

1 голос
/ 09 ноября 2011

Попробуйте это:

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

И соответственно измените ваши переменные.

0 голосов
/ 10 ноября 2011

Денис прав.

в ANSI C, i и j должны быть объявлены в начале функции:

int main()
{
int i,j;

...//instructions

 for( i=0; i<10; i++)
{
    for( j=0; j<50; j++)
    { ... }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...