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

C#中if/else if语句异常:始终执行第一个if分支问题排查

问题分析与解决

你的代码核心问题出在**Read()方法的错误使用**:

  • Console.Read()返回的是输入字符的ASCII码值,而非你输入的数字本身。比如输入37时,Read()只会读取第一个字符'3',它的ASCII码是51——51远大于39,因此程序会直接触发第一个if分支,输出"Allez à l'hopital"。

修正方案

改用**Console.ReadLine()**读取整行输入的字符串,再转换为整数,就能正确获取用户输入的温度值:

using System;
using static System.Console;

namespace E4_2
{
  internal class Program
  {
    static void Main(string[] args)
    {
        string texteÀAfficher;

        WriteLine("Veuillez indiquez la température du patient en celcius :");
        // 替换Read()为ReadLine(),读取完整输入行
        int temperature = Convert.ToInt32(ReadLine());

        if (temperature > 39)
        {
            texteÀAfficher = "Allez à l'hopital";
        }
        else if (temperature > 38)
        {
            texteÀAfficher = "Prendre de l'aspirine ou de l'eau";
        }
        else if (temperature > 37)
        {
            texteÀAfficher = "Se reposer";
        }
        else
        {
            texteÀAfficher = "Prendre l'air et bien s'habiller";
        }
        WriteLine(texteÀAfficher);
    }
}

额外优化建议

如果需要处理用户输入非数字的异常情况,可以用int.TryParse替代Convert.ToInt32,避免程序崩溃:

WriteLine("Veuillez indiquez la température du patient en celcius :");
if (int.TryParse(ReadLine(), out int temperature))
{
    // 原有的if-else判断逻辑
}
else
{
    WriteLine("Veuillez entrer une température valide (nombre entier).");
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 03:35:31