首页 > 解决方案 > 嵌套 for 循环背后的逻辑

问题描述

我正在学习 C++ 并尝试在两个周期内使用 C++ 中的嵌套 for 循环打印出以下内容。最后应该有 16 个 ADD 操作和 8 个 DELETE 操作:

ADD operation : Caller ID= 1 , Selected Queue= 2
ADD operation : Caller ID= 2 , Selected Queue= 2
ADD operation : Caller ID= 3 , Selected Queue= 1
ADD operation : Caller ID= 4 , Selected Queue= 1
ADD operation : Caller ID= 5 , Selected Queue= 1
ADD operation : Caller ID= 6 , Selected Queue= 2
ADD operation : Caller ID= 7 , Selected Queue= 0
ADD operation : Caller ID= 8 , Selected Queue= 1
DELETE operation : Caller ID= 1 , Selected Queue= 2
DELETE operation : Caller ID= 7 , Selected Queue= 0
DELETE operation : Caller ID= 2 , Selected Queue= 2
DELETE operation : Caller ID= 3 , Selected Queue= 1

我的代码是:

#include <stdio.h> // For printf function
#include <stdlib.h> // For srand and rand functions
#include <time.h> // For time function
#include <queue> // For STL queue class
#define N 2 // Number of simulation cycles
#define K 3 // Number of queues
#define IC 8 // Number of incoming calls per cycle (Number of ADD operations in a cycle)
#define FC 4 // Number of finished calls per cycle (Number of DELETE operations in a cycle)
using namespace std; // C++ requirement

int main()
{
    queue <int> Q[3]; // Array of STL queues (3 queues), which will store caller ID numbers
    int selected_queue; // Index of a randomly selected queue
    int caller_ID = 1; // Caller ID number
    int tmp_caller_ID; // Temporary caller ID
    srand(time(NULL)); // Seed (initialize) the random number generator
    int i,j;
    for(i=0;i<N;i++);
    {
        for(j=0;j<IC;j++);
        {
            selected_queue = rand() % 3; // Randomly determine the index number of a queue
            Q[selected_queue].push(caller_ID); // Add a caller ID number to the selected queue
            printf("ADD operation : Caller ID= %d , Selected Queue= %d \n", caller_ID, selected_queue);
            caller_ID++;
        }
        for(j=0;j<FC;j++);
        {
            selected_queue = rand() % 3; // Randomly determine the index number of a queue
            if (! Q[selected_queue].empty() ) // Check if the queue is not empty
                {
                    tmp_caller_ID = Q[selected_queue].front(); // Get (without deleting) a caller ID from selected queue
                    Q[selected_queue].pop(); // Delete a caller ID from the selected queue
                    printf("DELETE operation : Caller ID= %d , Selected Queue= %d \n", tmp_caller_ID, selected_queue);
                }
            else
            printf("DELETE operation : Selected Queue= %d (Queue is empty) \n", selected_queue);
        }
    }

}

但问题是,当我运行这段代码时,我得到:

ADD operation : Caller ID= 1 , Selected Queue= 2                                                                  
DELETE operation : Selected Queue= 0 (Queue is empty)

标签: c++for-loopnested

解决方案


您的语句末尾有一个for不属于那里的分号。

您的循环工作,但它们只在之后执行代码块,在您的示例中这是一个空语句。

删除分号,它应该可以正常工作。

例如for(i=0;i<N;i++);{应该阅读for(i=0;i<N;i++){


推荐阅读