坚持c中的增值税百分比



所以这是我的问题"写一个程序,要求用户输入一公斤西红柿的无税价格、你想买的公斤数和以百分比为单位的增值税。该程序必须写下总价。"我很好,直到VAT部分让我困惑。到目前为止,我已经得到了

Int32 a;
Int32 b;
Int32 c;
Int32 d;
Console.WriteLine("please enter the price of one kilo of tomatoes without VAT.");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the amount of kilos you want.");
b = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("please enter the amount of VAT.");
c = Convert.ToInt32(Console.ReadLine());
d = a * b;

所有货币金额都应存储为小数,而不是整数。如果你不清楚其中的区别,有很多很好的参考网站和教程可以解释C#数据类型。

英国增值税目前为20%,因此将20作为整数存储就足够了。但不久前增值税税率为17.5%,因此使用十进制变量更好。

此外,使用有意义的变量名而不是单个字母也是一个非常好的主意:

decimal price;
decimal quantity;
decimal vatRate;
decimal totalPrice;
Console.WriteLine("please enter the price of one kilo of tomatoes without VAT.");
price = Convert.ToDecimal(Console.ReadLine());
Console.WriteLine("Please enter the amount of kilos you want.");
quantity = Convert.ToDecimal(Console.ReadLine());
Console.WriteLine("Please enter the VAT rate. (Default = 20)");
decimal input;
if (Decimal.TryParse(Console.ReadLine(), out input))
{
    vatRate = input / 100;
}
else
{
    vatRate = 0.20M;
}
totalPrice = price * quantity * (1 + vatRate);
Console.WriteLine("Total price = {0}", totalPrice);

您还应该考虑将输出四舍五入到最接近的便士。

您应该将净价与增值税百分比相乘,然后将该金额添加到净价中。然后你应该把它和千克值相乘。但是,这种计算不应该使用int,因为int不保留浮点值。任何类型的财务计算都应该使用十进制。这样你就可以计算出确切的结果。

我认为你的代码应该是这样的:

Int32 a;
    Int32 b;
    Int32 c;
    decimal d;
    Console.WriteLine("please enter the price of one kilo of tomatoes without VAT.");
    a = Convert.ToInt32(Console.ReadLine());
    Console.WriteLine("Please enter the amount of kilos you want.");
    b = Convert.ToInt32(Console.ReadLine());
    Console.WriteLine("please enter the amount of VAT.");
    c = Convert.ToInt32(Console.ReadLine());
    d = ((decimal)a * (1 + (decimal)c / 100)) * b;
    Console.WriteLine(d);

还有3条建议。变量名称应该更具描述性。例如,d可以是result或vatIncludedAmount,或者更容易理解d是什么的东西。

a、 b和c应该是小数,因为净价可以是1.15美元,或者你可以买1.5公斤西红柿。当然,Convert.ToInt32应该是Convert.ToDecimal.

如果您检查用户输入,或者至少使用try-catch块来转换行,这将是很好的,因为用户可以输入不同于数字的内容。如果用户输入2kg,convert会抛出一个异常。

最新更新