首页 > 解决方案 > 我可以在 C 中使用嵌套的 do while 循环吗?

问题描述

我的任务是为火车时刻表创建一个简单的程序。我需要让用户输入将运行多少列火车以及火车将在一天中运行多少次。对于每次运行,我需要一次告诉一列火车去,其他火车待命,直到他们都跑完为止。我正在尝试使用嵌套的 do while 循环来实现这一点,但运气不佳。这是可能的还是我从一开始就错了?

如果用户输入 2 列火车将运行 2 次,我的输出将显示为:Train 1 go。所有其他列车待命。火车2去。所有其他列车待命。

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int numTrains = 0;
    int timeBlocks = 0;
    int numRuns = 1;
    int timeBlocksran = 0;

    printf("How many trains will be running today?\n");
    scanf("%d", &numTrains);

    printf("How many times will the trains run today?\n");
    scanf("%d", &timeBlocks);
    printf("OK. There will be %d trains running %d times today. Let's get them started. All Aboard.\n", numTrains, timeBlocks);
    do
    {
        timeBlocksran++;
        printf("Time Block %d\n", timeBlocksran);
        do
        {
            printf("Train %d go. All other trains standby.\n", numRuns);
            numRuns++;
        } while (numRuns <= numTrains);
    } while (timeBlocksran <= timeBlocks);

    return 0;
}

如果用户输入 2 列火车将运行 2 次,我希望我的输出为:TIME BLOCK 1 Train 1 go。所有其他列车待命。火车2去。所有其他列车待命。时间块 2 火车 1 去。所有其他列车待命。火车2去。所有其他列车待命。

标签: c

解决方案


推荐阅读