2013-03-13 34 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)); 

问题只是说变量,而不能是常量:)变量都会仍然乌龙