【问题标题】:Decimals to Integers [duplicate]小数到整数 [重复]
【发布时间】:2013-03-13 18:42:36
【问题描述】:

我在完成一项特定的家庭作业时遇到了问题。这似乎几乎是不可能的。问题是这样的......

“将来,您可能会使用其他不支持精确货币计算的小数类型的编程语言。在这些语言中,您应该使用整数执行此类计算。修改应用程序以仅使用整数进行计算复利。将所有货币金额视为整数的便士。然后分别使用除法和余数运算将结果分成美元和美分部分。显示结果时,在美元和美分部分之间插入句点。 "

当我按照说明使用整数时,我什至还没来得及除掉任何东西就得到了这些溢出错误。有谁知道如何使这项工作?这是需要修改的原始代码...

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

它得到了一些正确的数字,但由于某种原因开始吐出零。

【问题讨论】:

  • 良好编程习惯的一部分是选择有意义的变量名。 “数字”有什么作用?

标签: c# integer decimal console-application


【解决方案1】:

您每次都在通过循环更改amountnumber 的值,但我不认为这是您想要在这里做的。如果您在最终的 Console.WriteLine 调用中删除这些分配并更改参数(amount / 100amount % 100 在这里会有所帮助)您应该能够得到您正在寻找的结果。

【讨论】:

  • 我们的想法是一样的,我只是想让 Mikey 更加努力地工作。 (毕竟他的作业。)当它说“将所有货币金额视为整数便士”时,我认为这个问题非常慷慨,强烈暗示解决方案有点比“将原始代码中的每个数字乘以 100,进行数学运算,然后将答案除以 100 再打印出来”更微妙。
【解决方案2】:

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

问题只是说变量,而不是常量 :) 变量仍然是 ulong

【讨论】:

    猜你喜欢
    • 2011-06-02
    • 2013-10-30
    • 2021-05-21
    • 1970-01-01
    • 2011-11-03
    • 1970-01-01
    • 1970-01-01
    • 2016-01-19
    • 2015-12-07
    相关资源
    最近更新 更多