2013-03-13 48 views
-1

我遇到了特定的家庭作業任務。這似乎不可能。問題就像這樣......小數整數

「將來,您可能會使用其他編程語言,它們不具有支持精確貨幣計算的小數類型,在這些語言中,您應該使用整數執行此類計算。修改應用程序僅使用整數來計算複利,將所有貨幣金額視爲整數個便士,然後分別使用除法和餘數操作將結果分解爲美元和美分,插入美元和當您顯示結果時,美分部分。「

當我按照指示並使用整數時,在我甚至可以分割任何東西之前,我會得到這些溢出錯誤。有沒有人有任何想法如何使這項工作?下面是需要修改的原代碼...

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); 

它得到一些正確的數字,但後來開始吐出由於某種原因零。

+1

部分良好的編程習慣的是選擇有意義的變量名。 「號碼」的用途是什麼? – 2013-03-13 18:52:00

回答

0

您正在更改amountnumber每次循環的值,但我不認爲這就是您想要在此處執行的操作。如果您刪除了這些分配並更改了最終的Console.WriteLine呼叫中的參數,(amount/100amount % 100在此處會有所幫助),那麼您應該能夠獲得所需的結果。

+0

我們正在思考,我只是想讓Mikey的工作更難一點。 (畢竟,它*就是他的家庭作業。)當我說「把所有的貨幣數量當作整數的便士」這個問題時,我認爲這個問題相當慷慨,這暗示着解決方案比「乘法」將原始代碼中的每個數字加100,做數學運算,然後將答案除以100再打印出來「。 – 2013-03-13 19:14:26

0

((ulong)Math.Pow(100+ rate,year))會長得太快105^10> ulong。

我覺得老師讓他們把math.pow保留爲小數。

amount = (ulong)(Math.Round(principal * 
       Math.Pow((number + rate)/100.0, year),0)); 

      //display the year and the amount 
      Console.WriteLine("{0,4}{1,17}.{2,-2}", year, "$" + (ulong)(amount/number), (ulong)(amount % number)); 

問題只是說變量,而不能是常量:)變量都會仍然烏龍