C++:利率不会显示为 .06、.6 等

标签 c++ input output

我为一项作业创建了下面的程序。您应该能够输入您的原始本金、最低利率、最高利率和累积利息的年数。

测试后,一切正常,除非我输入最大利息为 0.06、.6 等。由于某种原因,它不会显示最大利息。如果我输入0.06作为最低利息,它会成功显示,如果我使用高于0.06的最高利息金额,它会显示0.06金额。没有其他金额给我带来问题。

有人可以帮助我弄清楚我需要更改什么来纠正这个问题吗?

#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

int main()
{
    //variables & named constants
    int principal = 0;
    double minimumInterest = 0.0;
    double maximumInterest = 0.0;
    int yearBase = 1;
    int years = 0;
    double balance = 0.0;

    //inputs
    cout << "Enter the beginning principal: $";
    cin >> principal;

    cout << "Enter the minimum interest rate: ";
    cin >> minimumInterest;

    cout << "Enter the maximum interest rate: ";
    cin >> maximumInterest;

    cout << "Enter the number of years the interest will accumlate: ";
    cin >> years;

    //calculations & loop
    do
    {
                  cout << "Year " << yearBase << ":" << endl; 
                  for (double rate = minimumInterest; rate <= maximumInterest; rate += .01)
                  {
                      balance = principal * pow(1 + rate, yearBase);

                      //display rate with zero decimal places
                      cout << fixed << setprecision(0);
                      cout << "     Rate " << rate * 100 << "%: $";

                      //display balance with two decimal places
                      cout << setprecision(2) << balance << endl;
                  }

                      //update years counter
                      yearBase +=1;       
    } while (yearBase <= years);
    system("pause");
    return 0;                   
}  

最佳答案

嗯,double不准确地表示十进制值:它是一个二进制浮点,即其内部表示为 _(-1)sign * significant * 2指数,其中符号为0或1,有效为无符号整数,指数 em> 有符号整数。这是一个相对简单的论证,表明您无法准确表示 0.01 或 0.6。即0.01加六十次的计算结果很可能不是0.6。事实上,如果你用足够的位数打印这些值,你就可以看到效果:

#include <iostream>
#include <iomanip>
#include <limits>

int main()
{
    double sum;
    double small(0.01);
    double big(0.6);

    for (int i(0); i != 60; ++i) {
        sum += small;
    }

    std::cout << std::setprecision(std::numeric_limits<double>::digits10 + 4)
              << "small=" << small << "\n"
              << "big=" << big << "\n"
              << "sum=" << sum << "\n";
} 

运行该程序将产生如下结果:

small=0.01000000000000000021
big=0.5999999999999999778
sum=0.6000000000000003109

如果您想查看计算使用的确切值,您需要将精度设置为 std::numeric_limits<double>::digits 。不过看起来不太漂亮。

现在有趣的问题是如何处理这样的问题?进行十进制数计算时,一般的解决方案是使用十进制 float ,但只有being proposed过程中存在。将被添加到 C++ 标准库中。您可以准确地维持利率。对于您的特定设置,最简单的方法可能是不使用利率来控制循环的执行,而是使用合适的计数器。

关于C++:利率不会显示为 .06、.6 等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13096187/

相关文章:

java - 在 Java 中集中处理输入

Matlab 将输出分成 2 个变量

c++ - 我想摆脱动态类型转换。最好的选择是什么?

具有两个名称但不带 : 的 C++ 结构定义

c++ - 如何分隔字符串并将标记传递给方法

c++ - 一行输入多个数字

C++ 结构错误 - 错误 C2061 : syntax error : identifier

c - 只读入一个或两个字符串

git - JQ - 如何定义过滤器以从输出数组中删除括号、引号和逗号

javascript - 每当对象内容发生更改时,Angular 就会触发 EventEmitter