我遇到了特定的家庭作業任務。這似乎不可能。問題就像這樣......小數整數
「將來,您可能會使用其他編程語言,它們不具有支持精確貨幣計算的小數類型,在這些語言中,您應該使用整數執行此類計算。修改應用程序僅使用整數來計算複利,將所有貨幣金額視爲整數個便士,然後分別使用除法和餘數操作將結果分解爲美元和美分,插入美元和當您顯示結果時,美分部分。「
當我按照指示並使用整數時,在我甚至可以分割任何東西之前,我會得到這些溢出錯誤。有沒有人有任何想法如何使這項工作?下面是需要修改的原代碼...
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