Question

sI am learning C++ and I keep getting a strange error. setprecision is giving me multiple decimal points in the one answer.

Why doe the output have multiple decimal points?

Program

#include<iostream>
#include<iomanip>
#include<math.h>
using namespace std;

int main () {

    int time, counter, range;
    double investment, rate, balance;

    cout << "Investment amount: " << endl;
    cin >> investment;
    cout << "Rate: " << endl;
    cin >> rate;
    cout << "Length of time: " << endl;
    cin >> time;    
    cout << "Incremental Range: " << endl;
    cin >> range;

    balance = 0;
    counter = 0;    

    cout << "\n\n\nRate \t 5 Years \t 10 Years \t 15 Years \t 20 Years \t 25 Years \t 30 Years \n" << endl;
    cout << fixed << setprecision(2);


    while(counter < 6)
    {
        counter = counter + 1;

        balance = investment * pow((1+ rate/100), time);

        cout << setw(2) << rate << setw(12) << balance;

        time = time + range;
    }

    cout << endl;


    return 0;    
}

Output

Rate     5 Years     10 Years    15 Years    20 Years    25 Years    30 Years 

5.00     1276.285.00     1628.895.00     2078.935.00     2653.305.00     3386.355.00     4321.94

As you can see 1276.285.00 etc should be 1276.28.

Why does the output have multiple decimal points?

Was it helpful?

Solution

I don't think you want to write rate each iteration:

cout << setw(2) << rate << setw(12) << balance;

The last part of "double-decimal-point" number is your rate.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top