【问题标题】:Why does my loop only work for the first few iterations?为什么我的循环只适用于前几次迭代?
【发布时间】:2014-06-04 02:36:59
【问题描述】:

我正在编写一个模拟超市结账线的代码。我使用动态分配(队列)来解决这个问题。 当前时间将从 0 到 120 分钟(这也是我循环的 120 次迭代) 每个客户将随机进入队列(下一个人将在 1 到 4 分钟的随机整数间隔后进入)。店员也会以随机的时间方式(1-4分钟后)为客户服务。 执行如下:

----1号客户到了

-当前时间为0

-当前时间为1

----左1号客户

-当前时间是2

----2号客户到了

-当前时间是3

----3号客户到了

----剩下的2号客户

等等。

函数入队帮助我将下一个客户添加到行中。 函数出队帮助我移除正在服务的客户。 这是先进先出队列。 第一个进入的人将是第一个离开队伍的人。

我的问题是:我的程序可以完美运行大约 60 或 70 个循环。在这些循环之后,我只看到有人进入线路,而不再看到有人离开线路。 如何修复此循环? 我的代码是:

 struct customer{
int number;  //show the order of the customer waiting on the line
struct customer *nextPtr; //point to the next customer
 };
 typedef struct customer Customer;
 typedef Customer *CustomerPtr;
int main (void)
{
  srand(time(NULL));
  CustomerPtr startPtr=NULL;
  int timework=0;
  int timein=0;
  int timeout=0;
  int customerio=1;// show the order of the customer entering the line
  printf("\tCustomer number %d arrived\n", customerio);
  enqueue(&startPtr, customerio);
  timein+=rand()%4+1; //schedule the time the next customer will enter the line
  timeout+=rand()%4+1; //schedule the time the next customer will leave the line

while (timework<=120){ // the clerk will serve customers for 120 minutes
    printf("Current time is %d\n", timework);
    if (timework==timeout){ //if the current time matches the time scheduled
        if (startPtr!=NULL){
            printf("\tCustomer number %d left\n", startPtr->number);
            dequeue(&startPtr); //remove a customer from queue
            timeout+=rand()%4+1;
        }
    }
    if (timework==timein){  //if the current time matches the time scheduled
        customerio+=1;
        printf("\tCustomer number %d arrived\n", customerio);
        enqueue(&startPtr, customerio);  //add a customer to queue
        timein+=rand()%4+1;
    }

    timework++; //time elapses to the next minute
}
return 0;
}

【问题讨论】:

  • 为什么我的问题有人反对?我已尽力解释我的问题

标签: c loops data-structures linked-list queue


【解决方案1】:

如果您遇到空队列(statePtr == NULL),那么您不会更新超时,因此它总是少于时间工作。通过移动更新您的代码

timeout+=rand()%4+1;

在检查 statePtr 的条件之外。

或者,将您的条件检查更改为timework &gt;= timeout,但这可能不太明显/有效。

其他解决方案是可能的 - 是否正确取决于模拟的性质。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-13
    • 1970-01-01
    • 2023-01-30
    • 1970-01-01
    • 2021-01-07
    • 1970-01-01
    • 1970-01-01
    • 2019-01-10
    相关资源
    最近更新 更多