此代码的问题是在 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 循环中重新定义变量,这完全没有意义。
这是代码的编译版本,但它看起来运行无限循环,但它可以编译。
关于c - 无限循环 (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28288981/