【发布时间】:2013-08-27 10:33:35
【问题描述】:
我一直在尝试将打印出来的答案精确到小数点后两位。所涉及的所有数学运算都必须保持小数点后两位的格式。我已经尝试了一些事情,但我不确定要进行哪些更改才能使这项工作正常进行。
double pdt1 = 239.99;
double pdt1Total;
double pdt2 = 129.75;
double pdt2Total;
double pdt3 = 99.95;
double pdt3Total;
double pdt4 = 350.89;
double pdt4Total;
double wage = 200;
double percentage = 9;
double total;
double answer;
double i = 100;
double a;
double b;
double c;
double d;
Console.Write("Enter number sold of product #1: ");
a = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter number sold of product #2: ");
b = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter number sold of product #3: ");
c = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter number sold of product #4: ");
d = Convert.ToInt32(Console.ReadLine());
pdt1Total = a * pdt1;
pdt2Total = b * pdt2;
pdt3Total = c * pdt3;
pdt4Total = d * pdt4;
total = (pdt1Total + pdt2Total + pdt3Total + pdt4Total);
string.Format("{0:0.00}", total);
string.Format("{0:0.00}", answer = (total * percentage / i) + wage);
Console.WriteLine("Earnings this week: "+answer+"");
【问题讨论】:
-
您可能不想使用浮点数作为货币 - 舍入错误最终会影响您。似乎没有内置任何东西,但请参阅codeproject.com/Articles/28244/A-Money-type-for-the-CLR 之类的链接以获取灵感。话虽如此,当你开始做百分比计算之类的事情时,你真的无法避免添加更多的小数位......
-
我需要双打始终保持在小数点后两位,但答案不会反映这一点。所以格式为:209.00(如果您为产品 3 选择 1 个产品,为所有其他产品选择 0,这应该是答案。)
-
你得到什么答案?
-
我得到了 108.9955,但现在使用 Damith 的代码它可以工作了。