You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#分阶段倒计时程序无法执行步长为5的递减逻辑求助

问题根因
  • Decrement方法逻辑不符合需求:当前实现会从传入的初始值直接按步长输出到0,方法执行完成后remainingTime会被修改为小于0的值,第一次调用步长10的逻辑后就已经不满足后续分支的判断条件,自然无法触发步长5的代码段。
  • while循环每个分支后都加了break语句,只要命中任意分支就会直接终止整个循环,就算修改了Decrement逻辑,也只会执行一次就退出。
修复后完整代码
static void Main(string[] args)
{
    int initialTime = Convert.ToInt32(Console.ReadLine());
    int remainingTime = initialTime;
    while (remainingTime > 0)
    { 
        if (remainingTime > 30)
        {
            Decrement(ref remainingTime, 10, 30);
        }
        else if (remainingTime > 10)
        {
            Decrement(ref remainingTime, 5, 10);
        }
        else
        {
            Decrement(ref remainingTime);
        }
    }
    Console.Read();
}

static void Decrement(ref int baseValue, int step = 1, int endThreshold = 0)
{
    for (int i = baseValue; i >= endThreshold; i -= step)
    {
        Console.WriteLine(i);
    }
    // 循环结束后设置下一段递减的起始值
    baseValue = endThreshold - 1;
}
修改说明
  • 给Decrement方法新增endThreshold参数,指定当前段递减的终止数值,方法执行到输出该数值后就停止,不会一直减到0
  • 移除while循环内所有break语句,让循环可以持续执行直到倒计时全部结束
  • 调整分支判断为if-else if-else结构,避免不必要的条件判断
  • 移除Main方法末尾冗余的0输出逻辑,最后一段步长1的递减会自动输出0

内容的提问来源于stack exchange,提问作者Constantin94

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 00:06:04