我遇到了特定的家庭作业分配问题。这似乎不可能。问题就像这样......使用整数而不是小数
“将来,您可能会使用其他编程语言,它们不具有支持精确货币计算的小数类型,在这些语言中,您应该使用整数执行此类计算。修改应用程序仅使用整数来计算复利,将所有货币金额视为整数个便士,然后分别使用除法和余数操作将结果分解为美元和美分,插入美元和当您显示结果时,美分部分。“
当我按照指示并使用整数时,在我甚至可以分割任何东西之前,我会得到这些溢出错误。有没有人有任何想法如何使这项工作?下面是需要修改的原代码...
decimal amount; //amount on deposit at end of each year
decimal principal = 1000; //initial amount before interest
double rate = 0.05; //interest rate
//display headers
Console.WriteLine("Year{0,20}", "Amount on deposit");
//calculate amount on deposit for each of ten years
for (int year = 1; year <= 10; year++)
{
//calculate new amount for specified year
amount = principal *
((decimal)Math.Pow(1.0 + rate, year));
//display the year and the amount
Console.WriteLine("{0,4}{1,20:C}", year, amount);
}
这是我到目前为止的代码...
long amount; //amount on deposit at end of each year
long principal = 100000; //initial amount before interest
long rate = 5; //interest rate
long number = 100;
//display headers
Console.WriteLine("Year{0,20}", "Amount on deposit");
//calculate amount on deposit for each of ten years
for (int year = 1; year <= 10; year++)
{
//calculate new amount for specified year
amount = principal *
((long)Math.Pow(100 + rate, year));
amount /= number;
number *= 10;
//display the year and the amount
Console.WriteLine("{0,4}{1,20}", year, amount);
它得到一些正确的数字,但后来开始吐出由于某种原因负数。
你是怎么修改代码的?什么是实际的错误信息? – geoffspear 2013-03-13 17:22:18
也许你应该首先遵循问题规范中的建议。我在代码中看到int和long之外的多种数据类型。 – 2013-03-13 17:24:15
我编辑了我原来的帖子,包括我目前使用的代码。 – 2013-03-13 17:55:22