【问题标题】:Using integer instead of decimal使用整数而不是小数
【发布时间】:2013-03-01 19:00:24
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • 你是怎么修改代码的?实际的错误消息是什么?
  • 也许您应该从遵循问题规范中的建议开始。我在您的代码中看到了除 int 和 long 之外的数据类型的多种用途。
  • 我已经编辑了我的原始帖子以包含我目前拥有的代码。

标签: c# integer decimal console-application


【解决方案1】:

只是给你一个提示:

int amount;

//...some code...
//let's pretend we have an amount of 100.97
amount = (int)(100.97 * 100); // amount = 10097

【讨论】:

    【解决方案2】:

    Math.Pow 使用双精度。用不了多久。
    在下一行中,您隐含地将您的费率和年份翻倍。

    amount = principal *
        ((long)Math.Pow(100 + rate, year));
    

    所以你实际上是在这样做:

    double dRate = (double)(100 + rate);
    double dYear = (double)year;
    double dPow = Math.Pow(dRate, dYear);
    amount = principal * (long)dPow;
    

    如果你想让你的 Pow 函数真正使用 long,那么你可能需要自己编写它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-06
      • 1970-01-01
      • 2014-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-05
      相关资源
      最近更新 更多