【问题标题】:Stuck in infinite loop (C)陷入无限循环 (C)
【发布时间】:2015-04-02 02:41:09
【问题描述】:

问题是代码在beetleSimulation 下的while 循环中,当x/yCount 超出范围时,它会一直运行而不是退出。 xy 远远超过 20,谁能帮我解释为什么?

#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);
}

【问题讨论】:

标签: c loops infinite


【解决方案1】:

目前,您的循环条件将始终为真,请记住,如果有任何条件为真,则使用 or 运算符,整个表达式将计算为真。

您可能希望 ands 出现在您的 while 循环条件中。只有当所有条件都为真时,循环才会继续。

while(xCount > -20 && xCount < 20 && yCount > -20 && yCount < 20)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-13
    相关资源
    最近更新 更多