-1

这段代码的问题是在 beetleSimulation 下的 while 循环中,当 x/yCount 超出范围时,它会永远持续而不是退出。x 和 y 远远超过 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 != 2 ) // argc should be 2 for correct execution 
        {
            // If the number of arguments is not 2
            printf("%d", argc);
        }
        else 
        {
           //run the bee

tle 模拟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);
}
4

2 回答 2

0
  • 你需要声明beetleSimulation

  • 您的变量在beetleSimulation 定义中没有类型

  • 您的 printf 语句是错误的。您需要使用 %d 并将其括在引号中。

  • 主要没有回报

  • 您还在逻辑中声明变量,您需要在函数顶部执行此操作(ANSI)

  • 在你的主要,2个参数是argv [0]和argv [1],所以a.out NUMBER

您的甲虫模拟功能需要 2 个输入,因此您需要 3 个参数。

  • 您在 while 循环中重新定义变量,这完全没有意义。

http://pastebin.com/RuuVDJdp

这是您的代码的编译版本,但是它似乎运行了一个无限循环,但它可以编译。

于 2015-02-02T23:57:34.463 回答
0

由于代码使用||但需要无限循环&&
xCount < 20 || xCount > -20永远是真的

// while(xCount < 20 || xCount > -20 || yCount <20 || yCount >-20){
while(xCount < 20 && xCount > -20 && yCount <20 && yCount >-20){
于 2015-02-03T01:09:42.517 回答