c - 无限循环 (C)

标签 c warnings declaration implicit-declaration

此代码的问题是在 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

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

最佳答案

  • 您需要声明 beetleSimulation

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

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

  • main没有返回

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

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

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

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

http://pastebin.com/RuuVDJdp

这是代码的编译版本,但它看起来运行无限循环,但它可以编译。

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

相关文章:

c - 似乎没有调用 ex19 Learn C The Hard Way 中的 void *self

c - 在 C 中声明一个只有 2 个小数点的变量

c - 为什么 float 相乘没有错误?

c++ - 在 C++ 中的函数声明之后不需要分号 (';' ) 吗?

C++,改变地址指针指向(指向一个常量值)

C 将结构分配给结构,现在变得非常烦人

ruby-on-rails - 我应该对 Rails 弃用警告感到害怕吗?

haskell - 避免在 GHCI 中出现不适当的非详尽模式匹配警告

Java:定义术语初始化、声明和赋值

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP