我遇到了特定的家庭作业任务。这似乎不可能。问题就像这样......小数整数
“将来,您可能会使用其他编程语言,它们不具有支持精确货币计算的小数类型,在这些语言中,您应该使用整数执行此类计算。修改应用程序仅使用整数来计算复利,将所有货币金额视为整数个便士,然后分别使用除法和余数操作将结果分解为美元和美分,插入美元和当您显示结果时,美分部分。“
当我按照指示并使用整数时,在我甚至可以分割任何东西之前,我会得到这些溢出错误。有没有人有任何想法如何使这项工作?下面是需要修改的原代码...
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);
}
这是我到目前为止的代码...
ulong amount; //amount on deposit at end of each year
ulong principal = 100000; //initial amount before interest
ulong rate = 5; //interest rate
ulong 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 *
((ulong)Math.Pow(100 + rate, year));
amount /= number;
number *= 10;
//display the year and the amount
Console.WriteLine("{0,4}{1,20}", year, amount);
它得到一些正确的数字,但后来开始吐出由于某种原因零。
部分良好的编程习惯的是选择有意义的变量名。 “号码”的用途是什么? – 2013-03-13 18:52:00