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

C#入门实现年龄分类控制台应用:禁止使用else关键字的实现问题

解答

  • 你当前代码中使用的else if确实包含else关键字,不符合题目禁止使用else的要求
  • 由于限定只能使用基础if语法,使用switch语句不符合本次练习的知识点要求

可选实现方案

方案1:默认值+单if判断(更推荐,冗余度低)

先给分组设置默认值,仅当满足另一条件时修改分组值,全程不需要用到else:

static void Main(string[] args)
{
    // 原输出为荷兰语,含义:请输入您的名字、姓氏和年龄
    Console.WriteLine("Vul uw voornaam, familienaam en leeftijd in.");
    
    string voorNaam = Console.ReadLine();
    string familieNaam = Console.ReadLine();
    int leeftijd = int.Parse(Console.ReadLine());
    
    // 默认赋值为成年人分组
    string groep = "Volwassen";
    if (leeftijd < 18)
    {
        groep = "Jeugd";
    }

    Console.WriteLine($"{voorNaam} {familieNaam}: {groep}");
    Console.ReadLine();
}

方案2:两个独立if判断(改动最小)

年龄小于18和大于等于18的条件完全互斥,直接把你原有代码的else关键字删掉,改成两个独立的if分支即可:

static void Main(string[] args)
{
    Console.WriteLine("Vul uw voornaam, familienaam en leeftijd in.");
    
    string voorNaam = Console.ReadLine();
    string familieNaam = Console.ReadLine();
    int leeftijd = int.Parse(Console.ReadLine());
    
    string groepJeugd = "Jeugd";
    string groepVolwassen = "Volwassen";
    
    if (leeftijd < 18)
    {
        Console.WriteLine($"{voorNaam} {familieNaam}: {groepJeugd}");
    }
    if (leeftijd >= 18) 
    {
        Console.WriteLine($"{voorNaam} {familieNaam}: {groepVolwassen}");
    }
    Console.ReadLine();
}

两种方案均完全符合仅使用基础if、不使用else的要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 16:48:04