The problem is that the code is in the while loop under beetleSimulation
, it goes on forever instead of exiting when x/yCount
goes out of the bounds. x
and y
go on much further than 20, can anyone help me out to why?
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define PI 3.14159265
void beetleSimulation(int, int);
int main ( int argc, char *argv[] )
{
if ( argc != 3 ) // argc should be 2 for correct execution
{
// If the number of arguments is not 2
printf("Program only has %d arguments ", argc);
return 0;
}
else
{
//run the beetle simulation
beetleSimulation(atoi(argv[1]), atoi(argv[2]) );
return 0;
}
}
void beetleSimulation(int size, int iterations){
int i;
double xCount = 0;
double yCount = 0;
int timeCount = 0;
int overallCount = 0;
int degree;
double radian;
for(i=0; i < 10; i++){
while(xCount < 20 || xCount > -20 || yCount <20 || yCount >-20){
timeCount += 1;
degree = rand() % 360;
radian = degree / (180 * PI);
xCount += sin(radian);
yCount += cos(radian);
printf("X and Y are %f and %f\n", xCount, yCount);
}
//when beetle has died, add time it took to overall count, then go through for loop again
overallCount += timeCount;
}
//calculate average time
double averageTime = overallCount/iterations;
printf("Average Time is %f",averageTime);
}
Currently your loop condition will always be true remember that with the or operator if any of the conditions are true the whole expression will evaluate to true.
You would want ands in your while loop condition instead. With them the loop will continue only if all of the conditions are true.
while(xCount > -20 && xCount < 20 && yCount > -20 && yCount < 20)