繁体   English   中英

计算错误

[英]Incorrect calculation

在C#编程中,我正在与Operators一起工作,但是我陷入了以下错误,即小费和税金的值与预期不符。

我的控制台应用程序的代码:

class OPerators
{
    static void Main(string[] args)
    {
        Console.WriteLine("Enter the MealCost");

        double mealCost = double.Parse(Console.ReadLine());
        int tipPercent = int.Parse(Console.ReadLine());
        int taxPercent = int.Parse(Console.ReadLine());

        // calulation Part

        // here i am getting the value of tip is 0.
        double tip = mealCost * (tipPercent / 100); 

        // here also value of tax is 0.
        double tax = mealCost * (taxPercent / 100);  

        double totalCost = mealCost + tip + tax;

        Console.WriteLine(Math.Round(totalCost));
        Console.ReadLine();

    }
}

我如何获得tiptax的价值?

我试过了:

double a = (tipPercent /100); 
tip = mealCost *a;

但它不起作用。

应当指出, Decimal应用于货币值。
关于您自己的问题,您可以使用下面的代码以获得预期的结果:

        Console.WriteLine("Enter the MealCost");

        decimal mealCost = Decimal.Parse(Console.ReadLine());
        int tipPercent = Int32.Parse(Console.ReadLine());
        int taxPercent = Int32.Parse(Console.ReadLine());

        // calulation Part

        decimal tip = mealCost * ((decimal)tipPercent / 100m);
        decimal tax = mealCost * ((decimal)taxPercent / 100m); 

        decimal totalCost = mealCost + tip + tax;

        Console.WriteLine(Math.Round(totalCost));
        Console.ReadLine();

使用以下命令将带括号的计算的输出更改为浮点数:

double tip = mealCost * (tipPercent / 100.0);
double tax = mealCost * (taxPercent / 100.0); 

您将整数除以100,如果数字小于100,则整数将始终返回0。typecasting tipPercent和taxPercent要加倍将解决您的问题。

double tip = mealCost * ((double)tipPercent / 100);

希望这可以帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM