c - 陷入无限循环 (C)

标签 c loops infinite

问题是代码在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);
}

最佳答案

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

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

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

关于c - 陷入无限循环 (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28289816/

相关文章:

grails - Grails遍历 Controller 中的对象

java - 有没有办法让这个脉冲数无限大?

javascript - NodeJS - 无限滚动

c - MISRA C2012 :10. 示例代码中存在 8 违规

java - 嵌套循环的顺序对速度有影响吗

loops - for循环方案

python - 而无限循环python

c++ - 一次从文件中读取字符 block ,并在 C 的下一个循环中读取下一个 block

c - 获取命令行的元素并将它们存储到数组中

c - 数据请求仅返回地址值(I2C)