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

C#单利复利计算程序输出Invalid问题求助

问题:C#利息计算程序输入选项后始终输出"Invalid"

控制台输出

Enter the amount:
20000
Enter the rate:
5 
Enter the time:
10
1.Si
2.Ci
 Select the option
1
Invaild

问题代码

using System;
class interest
{
    public static void Main()
    {
        double p, t, r, si, ci;
        Console.WriteLine("Enter the amount:");
        p = double.Parse(Console.ReadLine());
        Console.WriteLine("Enter the rate:");
        r = double.Parse(Console.ReadLine());
        Console.WriteLine("Enter the time:");
        t = double.Parse(Console.ReadLine());
        Console.WriteLine("1.Si\n2.Ci\n Select the option");
        string ch=Console.ReadLine();
        if (ch == "Si")
        {
            si = (p * r * t) / 100;
            Console.WriteLine("Simple Interest=" + si);
        }
        else if (ch == "Ci")
        {
            ci = p * Math.Pow(1 + (r / 100), t) - p;
            Console.WriteLine("Compund Interest=" + ci);
        }
        else 
            Console.WriteLine("Invaild");
        
    }
    
}

错误原因

程序的条件判断逻辑和用户输入不匹配:代码里判断输入字符串是否等于"Si"或"Ci",但实际提示用户输入的是1或2,两者完全不相等,所以每次都会进入else分支输出"Invaild"(注:此处单词拼写错误,正确应为Invalid)。

修正方案

修改条件判断,匹配用户实际输入的"1"和"2",同时对输入做Trim()处理,避免用户输入空格导致的匹配失败:

using System;
class interest
{
    public static void Main()
    {
        double p, t, r, si, ci;
        Console.WriteLine("Enter the amount:");
        p = double.Parse(Console.ReadLine());
        Console.WriteLine("Enter the rate:");
        r = double.Parse(Console.ReadLine());
        Console.WriteLine("Enter the time:");
        t = double.Parse(Console.ReadLine());
        Console.WriteLine("1.Si\n2.Ci\n Select the option");
        // 去除输入前后的空格,避免空格导致匹配失败
        string ch = Console.ReadLine().Trim();
        if (ch == "1")
        {
            si = (p * r * t) / 100;
            Console.WriteLine("Simple Interest=" + si);
        }
        else if (ch == "2")
        {
            ci = p * Math.Pow(1 + (r / 100), t) - p;
            Console.WriteLine("Compound Interest=" + ci); // 修正单词拼写错误
        }
        else 
            Console.WriteLine("Invalid"); // 修正单词拼写错误
        
    }
    
}

测试结果

输入示例中的参数后选择1,会输出:

Simple Interest=10000

选择2则会输出:

Compound Interest=12577.892535549384

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 07:50:56