【问题标题】:Not getting the desired output for a C# program to calculate and display simple and compound interest没有获得 C# 程序所需的输出来计算和显示单利和复利
【发布时间】:2022-11-20 22:53:45
【问题描述】:

我将 C#c 代码输入到 visual studio 中,用于以下程序计算并显示输入的本金金额、时间和利率的单利和复利,但输出无效,但我需要输出为数字。

控制台输出:

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");
        
    }
    
}

我尝试了很多方法,例如更改方法和公式,但无论我尝试什么,我得到的输出对于单利和复利都是无效的。我应该得到如下图所示的结果。Reference

【问题讨论】:

    标签: c# .net


    【解决方案1】:

    您的示例运行显示您输入了1,但您正在测试ch == "Si"。将其更改为 ch == "1" 并在第二个测试中:ch == "2" 或使用带有 switch 语句的更灵活的解决方案:

    switch ch.ToLower()
    {
        case "1" or "si":
            si = (p * r * t) / 100;
            Console.WriteLine("Simple Interest=" + si);
            break;
        case "2" or "ci":
            ci = p * Math.Pow(1 + (r / 100), t) - p;
            Console.WriteLine("Compund Interest=" + ci);
            break;
        defualt:
            Console.WriteLine("Invaild");
            break;
    }
    

    这允许您通过忽略字母大小写来输入选项编号或选项文本。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-24
      • 2018-11-08
      • 1970-01-01
      • 1970-01-01
      • 2014-01-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多