I need help with C++ code issue

So, I can not understand or figure out how to get the payment amount like a decimal form. (EX: 752.62)

Also, I can not figure out how to not allow letters to be inputted. Would appreciate any help.












//Loan Payment Calculator


#include <iostream>
#include<cmath>

using namespace std;

enum credit {Excellent,Good,Fair,Bad};

double frand(double fMin, double fMax)
{
double f = (double)rand() / RAND_MAX;
return fMin + f * (fMax - fMin);
}
double CalcPayment(double p, double interestRate, int loan_term)
{
double r = (interestRate / 12) / 100;
int n = loan_term * 12;
double x = pow(+r, n);
return(p * r * x) / (x - 1);
}

int main()
{

double principal_amount;
int loan_term;
int credit_score;
double interest_Rate = 0;

//Checking if entry is valid for principal

cout << "Please enter the principal amount:";
cin >> principal_amount;
if (principal_amount < 0)
{
cout << "Principal amount is not entered correctly!" << endl;
return 0;
}

//Inputting creditscore and making sure it's a valid amount.

cout << "Please enter credit score:";
cin >> credit_score;

while (credit_score <= 0 || credit_score > 850)
{
cout << "Please enter valid credit score!";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cin >> credit_score;
}
//Error occurs if user types in credit score lower than 300
if (credit_score < 300)
{
cout << "Sorry loan amount is not offered at this low of credit rate." << endl;
return 0;
}
//Taking loan information and making sure its valid.

cout << "Please enter the term of loan:";
cin >> loan_term;

while (!(loan_term == 15 || loan_term == 10 || loan_term == 30))
{
cout << "Please enter loan term again(in 10,15,30 years only):";
cin >> loan_term;
}
//Enums based on credit score
credit customer_credit;
if (credit_score > 300 && credit_score < 689)
{
customer_credit = Bad;
}
else if (credit_score > 630 && credit_score <= 689)
{
customer_credit = Fair;
}
else if(credit_score >= 690 && credit_score <= 719)
{
customer_credit = Good;
}
else
{
customer_credit = Excellent;
}
//Random interest rate based on the enums
switch (customer_credit)
{
case 0:
interest_Rate = frand(2.75, 4);
break;
case 1:
interest_Rate = frand(4.01, 6.50);
case 2:
interest_Rate = frand(6.51, 8.75);
break;
case 3:
interest_Rate = frand(8.76, 10.50);
break;
}
//Calling functions used to find the monthly payment for the loan.

double monthly_payment = CalcPayment(principal_amount, interest_Rate, loan_term);
cout << endl;
cout << "Your monthly payments would come out to be:" << monthly_payment << "on your loan" << endl;
system("pause");

return 0;
}

Last edited on
Edit your post to use code tags.
[code]
your code here
[/code]

what
who
dumb
Do you see any major problems?
many here won't look at large code dumps until you format it. Edit the post and apply the tags so it has IDE like indents and syntax coloring etc.

Also try to explain what you want. All numbers are normal to me. Decimal numbers can be formatted by default, a fixed # of digits, a scientific notation, and more. Which of those means normal depends on your world view.
Last edited on
ok thanks
1) Please add [ code] [/ code] tags:
http://www.cplusplus.com/articles/jEywvCM9/

(otherwise, as jonnin warned you, your post could be ignored)


- - -
2) Consider outputting your calculations to debug your code.
1
2
3
4
5
6
7
double CalcPayment(double p, double interestRate, int loan_term)
{
    double r = (interestRate / 12) / 100;
    int n = loan_term * 12;
    double x = pow(+r, n);
    return(p * r * x) / (x - 1);
}

Your 'x' above can be very little and cause CalcPayment() to return a negative value ( (x - 1) becomes negative).


- - -
3) Beware using magic numbers.
1
2
3
4
5
if (credit_score > 300 && credit_score < 689)
{
    customer_credit = Bad;
}
else if (credit_score > 630 && credit_score <= 689)

I’m pretty sure the first “689” is wrong.


- - -
4) std::rand() needs to be initialized — see std::srand():
https://en.cppreference.com/w/cpp/numeric/random/srand
But please consider stopping using std::rand() at all.
Do use current pseudorandom C++ features instead.
(I’m adding an example code at the end of this post)


- - -
5) Get on splitting your code into functions and ‘empty’ main(). It will increase its readability a lot.


- - -
6)
I can not figure out how to not allow letters to be inputted

That’s an old chestnut… You can find several good solution surfing this forum, but none easy to describe. I’m adding one I like in my example code.

Example (yet to be tested!!):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
// So, I can not understand or figure out how to get the payment amount like a
// decimal form. (EX: 752.62)
// Also, I can not figure out how to not allow letters to be inputted.
//Loan Payment Calculator
#include <chrono>
#include <cmath>
#include <exception>
#include <iomanip>
#include <iostream>
#include <random>


enum Credit { Excellent, Good, Fair, Bad };


std::mt19937& getRndEngine();
double getRndDouble( double min = std::uniform_real_distribution<>().min(),
                     double max = std::uniform_real_distribution<>().max() );
double askForNum( double min, double max, const std::string& );
int askForNum( int min, int max, const std::string& );
int askForLoanTerms();
Credit reckonCustomerCredit( int credit_score );
double reckonRndInterestRate( Credit par );
double calcPayment(double p, double interest_rate, int loan_term);


int main()
{
    //Checking if entry is valid for principal
    double principal_amount { askForNum( 0.0,
                                         std::numeric_limits<double>::max(),
                                         "Please enter the principal amount:" ) };

    //Inputting creditscore and making sure it's a valid amount.
    int credit_score { askForNum( 0, 850, "Please enter credit score:" ) };

    //Error occurs if user types in credit score lower than 300
    if (credit_score < 300) {
        std::cout << "Sorry loan amount is not offered at this low of credit rate.\n";
        return 0;
    }

    //Random interest rate based on the enums
    double interest_rate {
        reckonRndInterestRate( reckonCustomerCredit(credit_score) )
    };

    int loan_term { askForLoanTerms() };

    //Calling functions used to find the monthly payment for the loan.
    double monthly_payment {
        calcPayment(principal_amount, interest_rate, loan_term)
    };

    std::cout << "\nYour monthly payments would come out to be: "
              << std::fixed << std::setprecision(2) << monthly_payment
              << " on your loan\n";
}


std::mt19937& getRndEngine()
{
    static std::mt19937 eng {
        static_cast<unsigned>(
            std::chrono::high_resolution_clock::now().time_since_epoch().count()
        )
    };
    return eng;
}


double getRndDouble( double min, double max )
{
    std::uniform_real_distribution<> dst( min, max );
    return dst( getRndEngine() );
}


double calcPayment(double p, double interest_rate, int loan_term)
{
    double r { (interest_rate / 12) / 100 };
    int n { loan_term * 12 };
    //                   \/ what is the point of this '+' ?
    double x { std::pow( +r, n ) };
    std::cout << std::fixed << std::setprecision(4)
              << "r: " << r << "; n: " << n << "; x: " << x
              << "\n(p * r * x) / (x - 1): " << (p * r * x) / (x - 1) << '\n';
    return (p * r * x) / (x - 1);
}


double askForNum( double min, double max, const std::string& str )
{
    double ret_val;
    std::cout << str << "\n>>> ";
    for (std::string s; std::cin >> s; /**/) {
        // or ... std::getline( std::cin, s) ...
        try {
            ret_val = std::stod( s );
        } catch (const std::exception& e) {
            std::cout << "Unknown value '" << s << "'. Please retry.\n"
                      << str << "\n>>> ";
            continue;
        }
        if (ret_val < min) {
            std::cout << ret_val << " is below the minimum accepted value "
                      << min << ".\nPlease retry.\n" << str << "\n>>> ";
            continue;
        }
        if (max < ret_val) {
            std::cout << ret_val << " is over the maximum accepted value "
                      << max << ".\nPlease retry.\n" << str << "\n>>> ";
            continue;
        }
        break;
    }
    std::cout << "Accepted value '" << ret_val << "'.\n";   // debug
    return ret_val;
}


int askForNum( int min, int max, const std::string& str)
{
    int ret_val;
    std::cout << str << "\n>>> ";
    for (std::string s; std::cin >> s; /**/) {
        // or ... std::getline( std::cin, s) ...
        try {
            ret_val = std::stoi( s );
        } catch (const std::exception& e) {
            std::cout << "Unknown value '" << s << "'. Please retry.\n"
                      << str << "\n>>> ";
            continue;
        }
        if (ret_val < min) {
            std::cout << ret_val << " is below the minimum accepted value "
                      << min << ".\nPlease retry.\n" << str << "\n>>> ";
            continue;
        }
        if (max < ret_val) {
            std::cout << ret_val << " is over the maximum accepted value "
                      << max << ".\nPlease retry.\n" << str << "\n>>> ";
            continue;
        }
        break;
    }
    std::cout << "Accepted value '" << ret_val << "'.\n";   // debug
    return ret_val;
}


int askForLoanTerms()
{
    switch (askForNum( 1, 3, "Please enter the term of loan.\n"
                             "1) 10 years\n2) 15 years\n3) 30 years" ))
    {
    case 1:  return 10;
    case 2:  return 15;
    case 3:  return 30;
    }
    return -1;      // just to avoid compiler warnings
}


Credit reckonCustomerCredit( int credit_score )
{
    //                   \/ check this value
    if (credit_score <  689) { return Credit::Bad; }
    if (credit_score <= 689) { return Credit::Fair; }
    if (credit_score <= 719) { return Credit::Good; }
    return Credit::Excellent;
}


double reckonRndInterestRate( Credit par )
{
    switch ( par ) {
    case Credit::Excellent:  return getRndDouble( 2.75, 4 );
    case Credit::Good:       return getRndDouble( 4.01, 6.50 );
    case Credit::Fair:       return getRndDouble( 6.51, 8.75 );
    case Credit::Bad:        return getRndDouble( 8.76, 10.50 );
    }
    return 0.0;         // just to avoid compiler warnings
}

What is the formula to calculate the payment? Does CalcPayment compute that formula?

Here is a test case showing the correct answer.
Please enter the principal amount:1000
Please enter credit score:600
Please enter the term of loan:10
Your monthly payments would come out to be: 13.1933 on your loan

Thanks, Enoizat!! that helps a lot and I will look into the tags!
Howdy. Many students really like writing essays, although writing it complicates the learning process. Let's be honest: the theoretical part of many of the works of young (and, too bad, not only young) scientists is just a compilation of other people's works, just at the end a postscript is made that sets out their own opinion. Of course, if you are a lazy student, no one forbids you to contact the company that deals with https://domyassignments.com/history-help.html history homework help.
Last edited on
Topic archived. No new replies allowed.