Search code examples
cwarningsdeclarationimplicit-declaration

Infinite loop (C)


The problem this this 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 != 2 ) // argc should be 2 for correct execution 
        {
            // If the number of arguments is not 2
            printf("%d", argc);
        }
        else 
        {
           //run the bee

tle simulation beetleSimulation(argv[1], argv[2] ); } }

void beetleSimulation(int size, int iterations){
    int i;
    int xCount = 0;
    int yCount = 0;
    int timeCount = 0;
    int overallCount = 0;
    for(i=0; i < 10; i++){
        while(xCount < 20 || xCount > -20 || yCount <20 || yCount >-20){
            timeCount += 1;
            int degree = rand() % 360;
            double radian = degree / 180 * PI;
            xCount += sin(radian);
            yCount += cos(radian);
        }

        //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("%d",averageTime);
}

Solution

    • You need to declare beetleSimulation

    • Your variables have no types in the beetleSimulation Definition

    • Your printf statements are just wrong. You need to use %d and wrap it in quotations.

    • main has no return

    • Your also declaring variables within your logic, you need to do that at the top of the function (ANSI)

    • In your main, 2 arguments is argv[0] and argv[1], so a.out NUMBER

    Your beetlesimulation function requires 2 inputs, so you need 3 arguments.

    • You're redefining variables in your while loop, that makes utterly no sense at all.

    http://pastebin.com/RuuVDJdp

    Here's a compiling version of your code, however it runs an infinite loop it seems, but it compiles.