我在完成一项特定的家庭作业时遇到了麻烦。这似乎几乎是不可能的。问题是这样的……
“将来,您可能会使用其他不支持精确货币计算的小数类型的编程语言。在这些语言中,您应该使用整数执行此类计算。修改应用程序以仅使用整数来计算复利. 将所有货币金额视为整数的便士。然后分别使用除法和余数运算将结果分成美元和美分部分。在显示结果时在美元和美分部分之间插入句点。
当我按照指示使用整数时,我什至在将任何内容分开之前就得到了这些溢出错误。有谁知道如何使这项工作?这是需要修改的原始代码...
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);
它得到了一些正确的数字,但由于某种原因开始吐出负数。