I can't figure out what's wrong with my c++ program - c++

The question is: The ABC Hardware Company has hired you to write a program for it's Account Receivable dept. The master file is in ascending order by customer number with a 20 character customer name and balance due. The transaction file contains records of each transaction with customer number. You are to read in records one at a time from the two files and use the transaction file to update the info from the master file. Process all transaction records before going on to the next master record. If the transaction record contains an "O" in column 1, calculate the orderamount and add it to the balance due. If the record contains a "P" in column 1, subtract the payment from the balance due. Keep a running total of the AR balance of the ABC Company (the sum of balances for each customer). After processing a master record and all its transactions, the program should prepare an invoice for each customer which lists the customer name, number, previous balance, all transactions, and the final balance due.
The output should look like:
CUSTOMER NAME CUSTOMER NUMBER
PREVIOUS BALANCE $XXX.XX
(ALL TRANSACTIONS PER CUSTOMER:)
TRANSACTION# ITEM ORDERED $ORDER AMOOUNT
TRANSACTION# ITEM ORDERED $ORDER AMOUNT
TRANSACTION# PAYMENT $PAYMENT AMOUNT
BALANCE DUE $XXX.XX
I've tried changing up the arrays, the if statements etc. Now nothing's printing at all when I run the program. Please help!
Here is the code I have so far:
# include <iostream>
# include <fstream>
# include <iomanip>
# include <string>
using namespace std;
struct master {
double custnum;
string name;
double balance;
};
struct transactions {
char transtype;
int custnum;
int transnum;
string item;
int quantity;
double price;
double amountpaid;
};
int main ()
{
ifstream masterfile ("MASTER.txt");
ifstream transfile ("TRANSACTION.txt");
int prevbalance[7];
master main [7];
for (int i=0; !masterfile.eof(); i++) {
masterfile>>main[i].custnum>>main[i].name>>main[i].balance;
}
for (int i=0;!masterfile.eof();i++) {
cout << main[i].custnum<<" ";
cout << main[i].name<<" ";
cout << main[i].balance<<" "<<
endl<<endl;
prevbalance[i] = main[i].balance;
}
double companybalance = 0;
double orderamt=0;
transactions tran[35];
for (int i=0; !transfile.eof(); i++) {{
transfile>> tran[i].transtype;
cout<<tran[i].transtype<<" ";
if (tran[i].transtype == 'O') {
transfile>>tran[i].custnum;
cout<<tran[i].custnum<<" ";
transfile>> tran[i].transnum;
cout<<tran[i].transnum<<" ";
transfile>>tran[i].item;
cout<<tran[i].item<<" ";
transfile>>tran[i].quantity;
cout<<tran[i].quantity<<" ";
transfile>>tran[i].price;
cout<<tran[i].price<<" "<<endl<<endl;
orderamt= tran[i].price*tran[i].quantity;
main[i].balance+= orderamt;
companybalance += main[i].balance;
}
else if (tran[i].transtype == 'P'){
transfile>>tran[i].custnum;
cout<<tran[i].custnum<<" ";
transfile>> tran[i].transnum;
cout<<tran[i].transnum<<" ";
transfile>>tran[i].amountpaid;
cout<<tran[i].amountpaid<<endl<<endl<<endl;
main[i].balance-tran[i].amountpaid;
companybalance += main[i].balance;
}}
for(int i=0; i<50; i++) {
cout<<"Name: "<< main[i].name <<" Customer #: "<< main[i].custnum<<endl<<endl;
cout<<"Previous Balance "<<prevbalance[i]<<endl;
for(int j=0; j<7; j++){
cout<<"Transaction #: "<<tran[j].transnum<<" "<<tran[j].item<<" $"<<orderamt<<endl; }
cout<<"Balance Due: "<<main[i].balance<<endl;
}
}}
Here are the input two files, Masterfile:
1000 TIFFANY 7000.99
2000 MARY 6500.98
3000 JACOB 6560.99
4000 GENE 4560.98
5000 BELLA 5300.87
6000 ANNA 2340.90
7000 DEMI 4230.45
and transaction file:
O 1000 1000 PENS 20 2
O 1000 2000 CPUS 2 200
O 1000 3000 MONITER 2 100
P 1000 4000 4000
P 1000 5000 300
O 2000 6000 CPUS 3 500
O 2000 7000 MOUSE 3 50
O 2000 8000 WIRES 5 8
P 2000 9000 600
P 2000 1100 798
O 3000 1200 MONITERS 6 60
O 3000 1300 CPUS 7 300
O 3000 1400 MOUSE 30 40
O 3000 1500 SPEAKERS 20 20
P 3000 1600 5000
O 4000 1001 SPEAKERS 2 50
O 4000 2002 CABLES 4 20
P 4000 3003 400
P 4000 4004 500
P 4000 5005 68
P 5000 6001 600
P 5000 4002 55
P 5000 2003 450
O 5000 4004 SPEAKERS 4 60
O 5000 1005 LAPTOP 3 300
O 6000 6001 TVS 5 400
O 6000 8002 SPEAKERS 5 70
P 6000 6003 2000
P 6000 8004 1000
O 6000 8005 CABLES 10 15
O 7000 5001 PENS 50 2
O 7000 7002 PAPER 400 2
P 7000 4003 150
P 7000 3004 230
P 7000 6005 450

You're using masterfile.eof() as a loop condition twice.
for (int i=0; !masterfile.eof(); i++) {
masterfile>>main[i].custnum>>main[i].name>>main[i].balance;
}
for (int i=0;!masterfile.eof();i++) {
cout << main[i].custnum<<" ";
cout << main[i].name<<" ";
cout << main[i].balance<<" "<<
endl<<endl;
prevbalance[i] = main[i].balance;
}
Think about how this couldn't possibly work. You've already reached the end of the file by the time the first loop ends. The second loop is going to finish before it even starts!
Of course you could reset the file pointer to the beginning but a much better way is to keep a count of the number of records you have, and use that count for the second loop.
int iRecordCount = 0;
for (iRecordCount = 0; !masterfile.eof(); iRecordCount++) {
masterfile>>main[iRecordCount].custnum>>main[iRecordCount].name>>main[iRecordCount].balance;
}
for (int i=0; i < iRecordCount;i++) {
cout << main[i].custnum<<" ";
cout << main[i].name<<" ";
cout << main[i].balance<<" "<<
endl<<endl;
prevbalance[i] = main[i].balance;
}
Also note that you're using a fixed array (master main[7]) to store your records - what happens if you have an input file with more than 7 records in it? You'll exceed the bounds of the array. Really you should change to using a std::vector so that the array can grow dynamically, but if you don't want to do that you should put an additional check in when reading the records to make sure you don't overflow the array:
int iRecordCount = 0;
for (iRecordCount = 0; iRecordCount < sizeof(main) / sizeof(main[0]) && !masterfile.eof();
iRecordCount++) {
masterfile>>main[iRecordCount].custnum>>main[iRecordCount].name>>main[iRecordCount].balance;
}
You're also doing something weird when reading your transactions. You have things like:
orderamt= tran[i].price*tran[i].quantity;
main[i].balance+= orderamt;
If i is the transaction number (tran[i]) how can it also be the customer number as well (main[i])? You're allowed to use variable names other than i you know!
You also have this at the bottom of your code:
for(int i=0; i<50; i++) {
....
}
Again, you should use the actual number of elements in the array (iRecordCount) rather than a fixed number (and where did 50 come from since your array is only 7 elements in size?).

In addition to the suggestions made by #JonathanPotter in his answer, I want to add that using ifstream.eof() in the for loop is error prone.
Useful reading material: Why is “while ( !feof (file) )” always wrong?.
Use of !masterfile.eof() in the conditional of a for loop is wrong for exactly the same reasons.
It's better to use:
std::vector<master> masterData;
while ( masterfile )
{
// Try to read the data into a temporary object.
master m;
masterfile >> m.custnum >> m.name >> m.balance;
// If the input was successful, add it to masterData
if ( masterfile )
{
masterData.push_back(m);
}
}
You can use similar logic to read the transaction records too.
Also, you have a line:
main[i].balance - tran[i].amountpaid;
I am sure that is a typo and you meant to use:
main[i].balance -= tran[i].amountpaid;

Related

Array Lookup test cases failing

So, this is one of two practice questions given by our professor on HackerRank. I came up with the code but the solution only passes 2/5 test cases. I tried thinking about the possible test cases that give an error for around 4 hours, but, I could not wrap my mind around it.
Can someone point out where I went wrong?
Below is the question.
Alice went for shopping and bought 8 goods costing different prices.
At the time of billing she realises that she did not have enough
money. Now, she have decided to remove the item costing maximum amount
and replace it with another item whose price is same as the item
costing minimum amount. Help Alice and display final prices on the
screen.
Note: if more than one element cost maximum price, replace the first
item.
Example 1:
Input: 250 1000 50 20 10 100 200 25
Output: 250 10 50 20 10 100 200 25
Example 2:
Input: 2500 2500 50 20 10 100 200 25
Output: 10 2500 50 20 10 100 200 25
Sample Input: 250 1000 50 20 10 100 200 25
Sample Output: 10 2500 50 20 10 100 200 25
Constraints
8 items prices are required
Output Format
Prints the final prices of different items after replacing
MY CODE:
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int arr[8];
int check=0;
int max=0,min=0;
for(int i=0;i<8;i++)
{
cin>>arr[i];
if(i==0)
{
max =arr[0];
min =arr[0];
}
else
if(arr[i]>max)
max = arr[i];
if(arr[i]<min)
min = arr[i];
}
for(int i=0;i<8;i++)
{
if(arr[i]==max && check==0)
{
arr[i]=min;
check++;
}
cout<<arr[i]<<" ";
}
}

Does fstream access the hardrive with read and writes during compile time if used within a class temlpate?

Consider the following code snippet of this class template...
template<class T>
class FileTemplate {
private:
std::vector<T> vals_;
std::string filenameAndPath_;
public:
inline FileTemplate( const std::string& filenameAndPath, const T& multiplier ) :
filenameAndPath_( filenameAndPath ) {
std::fstream file;
if ( !filenameAndPath_.empty() ) {
file.open( filenameAndPath_ );
T val = 0;
while ( file >> val ) {
vals_.push_back( val );
}
file.close();
for ( unsigned i = 0; i < vals_.size(); i++ ) {
vals_[i] *= multiplier;
}
file.open( filenameAndPath_ );
for ( unsigned i = 0; i < vals_.size(); i++ ) {
file << vals_[i] << " ";
}
file.close();
}
}
inline std::vector<T> getValues() const {
return vals_;
}
};
When used in main as such with the lower section commented out with the following pre-populated text file:
values.txt
1 2 3 4 5 6 7 8 9
int main() {
std::string filenameAndPath( "_build/values.txt" );
std::fstream file;
FileTemplate<unsigned> ft( filenameAndPath, 5 );
std::vector<unsigned> results = ft.getValues();
for ( auto r : results ) {
std::cout << r << " ";
}
std::cout << std::endl;
/*
FileTemplate<float> ft2( filenameAndPath, 2.5f );
std::vector<float> results2 = ft2.getValues();
for ( auto r : results2 ) {
std::cout << r << " ";
}
std::cout << std::endl;
*/
std::cout << "\nPress any key and enter to quit." << std::endl;
char q;
std::cin >> q;
return 0;
}
and I run this code through the debugger sure enough both the output to the screen and file are changed to
values.txt - overwritten are -
5 10 15 20 25 30 35 40 45
then lets say I don't change any code just stop the debugging or running of the application, and let's say I run this again 2 more times, the outputs respectively are:
values.txt - iterations 2 & 3
25 50 75 100 125 150 175 200 225 250
125 250 375 500 625 750 875 1000 1125 1250
Okay good so far; now lets reset our values in the text file back to default and lets uncomment the 2nd instantiation of this class template for the float with a multiplier value of 2.5f and then run this 3 times.
values.txt - reset to default
1 2 3 4 5 6 7 8 9
-iterations 1,2 & 3 with both unsigned & float the multipliers are <5,2.5> respectively. 5 for the unsigned and 2.5 for the float
- Iteration 1
cout:
5 10 15 20 25 30 35 40 45
12.5 25 37.5 50 62.5 75 87.5 100 112.5
values.txt:
12.5 25 37.5 50 62.5 75 87.5 100 112.5
- Iteration 2
cout:
60
150 12.5 62.5 93.75 125 156.25 187.5 218.75 250 281.25
values.txt:
150 12.5 62.5 93.75 125 156.25 187.5 218.75 250 281.25
- Iteration 3
cout:
750 60
1875 150 12.5 156.25 234.375 312.5 390.625 468.75 546.875 625 703.125
values.txt:
1875 150 12.5 156.25 234.375 312.5 390.625 468.75 546.875 625 703.125
A couple of questions come to mind: it is two fold regarding the same behavior of this program.
The first and primary question is: Are the file read and write calls being done at compile time considering this is a class template and the constructor is inline?
After running the debugger a couple of times; why is the output incrementing the number of values in the file? I started off with 9, but after an iteration or so there are 10, then 11.
This part just for fun if you want to answer:
The third and final question yes is opinion based but merely for educational purposes for I would like to see what the community thinks about this: What are the pros & cons to this type of programming? What are the potentials and the limits? Are their any practical real world applications & production benefits to this?
In terms of the other issues. The main issue is that you are not truncating the file when you do the second file.open statement, you need :
file.open( filenameAndPath_, std::fstream::trunc|std::fstream::out );
What is happening, is that, when you are reading unsigned int from a file containing floating points, it is only reading the first number (e.g. 12.5) up to the decimal place and then stopping (e.g. reading only 12)
, because there is no other text on the line that looks like an unsigned int. This means it only reads the number 12 and then multiplies it by 5 to get the 60, and writes it to the file.
Unfortunately because you don't truncate the file when writing the 60, it leaves the original text at the end which is interpreted as additional numbers in the next read loop. Hence, 12.5 appears in the file as 60 5
stream buffers
Extracts as many characters as possible from the stream and inserts them into the output sequence controlled by the stream buffer object pointed by sb (if any), until either the input sequence is exhausted or the function fails to insert into the object pointed by sb.
(http://www.cplusplus.com/reference/istream/istream/operator%3E%3E/)

QString line.split

I am having trouble with split function on QT. I have a text file and the very first line is like this:
10,100;100,100;100,100;100,200;100,200;300,200;300,200;300,350;300,350;250,350;250,350;250,300;250,300;200,300;200,300;200,400;200,400;10,400;10,400;10,100
Here every two numbers represents a point with x an y values and semicolons divides the points. After every semicolon there is a new point.
What I want to do is split these numbers element by element like;
Element 0: 10
Element 1: 100
Element 2: 100
Element 3: 100
...
I have managed to do this but there wasn't any semicolons or colons in the text file.
First line of the text file:
10 100 100 100 100 200 300 200 300 350 250 350 250 300 200 300 200 400 10 400 10 100
This is how i did it:
void Dialog::readFile()
{
QFile file("/Path/of/the/text/file/Data.txt");
if(!file.open(QIODevice::ReadOnly)) {
QMessageBox::information(0, "info", file.errorString());
}
QString line = file.readLine();
qDebug() << "line:" << line << "\n";
QStringList list = line.split(" ");
double element;
for(int i = 0; i < list.size(); i++) {
element = list.at(i).toDouble();
points_.append(element);
qDebug() << "element:" << element << "\n";
}
}
Output of this code is:
line: "10 100 100 100 100 200 300 200 300 350 250 350 250 300 200 300 200 400 10 400 10 100\r"
element: 10
element: 100
element: 100
element: 100
element: 100
element: 200
element: 300
element: 200
....
I want to do this exactly the same way. Is there any suggestion?
PS: I am new on QT so please consider this.
You can use regular expression with the QString::split overload taking QRegExp or the next one taking QRegularExpression:
QStringList list = line.split(QRegExp(",|;")); // ",|;" matches ',' or ';'
QRegExp is called to be deprecated, but it can do the job here.

Probability of choosing two cities C++

I'm making a program where I have a list of 34 cities and I am wanting to give each of these cities a probability of being chosen.
So I have:
vector<float> vec;
int s;
cin >> s;
srand(s);
for (int k=0; k < 34; k++)
{
float p1= (float)rand()/(float)((unsigned)RAND_MAX+1);
vec.push_back(p1);
}
So that gives each city a probability. The problem I am now having is I want to then do a random number generator that will choose two of these cities. So, for example city1 will have a 5%, city2 a 2%, city3, a 3%, etc. How can I randomly choose two of these cities based off the probabilities given?
I did this in genetic algorithm.
for your cities consider a line of 10 units.
now from 0-5 units on line are city1 6-7 for city2 and 8-9 for city3.
now choose a number at random from 0-9.
and found out in which cities range it comes in.
At first glance my solution will be :
Create a number equals to all city's probability
Create a random number, with max random number is equal to the previous number
Take the random number, and go throught your city vector and take the one who is corresponding.
Example :
City 1 : 5%
City 2 : 8%
City 3 : 2%
City 4 : 5%
City 5 : 12%
Create a number -> Number a = 32 (5+8+2+5+12)
Generate a number with : 1 <= number
Assume that the number is equal to 12
City 1 is choose if : 1 <= number <= 5 (So not)
City 2 is choose if : 6 <= number <= 13 (So yes)
City 2 is choose.
If you have any questions about that, you are welcome :)
Edit :
Well i will give you some more explaination.
Take this code :
for (int k=0; k < 10; k++)
{
float p1= (float)rand()/(float)((unsigned)RAND_MAX+1);
vec.push_back(p1);
}
Assume now that vec contain the following informations :
5
3
8
5
12
14
8
5
6
18
With each number correspond to the probability to choose a city.
5 -> 5% probability to choose (City1)
3 -> 3% probability to choose (City2)
8 -> 8% probability to choose (City3)
... etc
Now i will give you some code and i will explain it :
int nbReference = 0;
for (auto it = vec.begin() ; it != vec.end() ; ++it)
{
nbReference += *it;
}
nbReference = rand(nbReference);
int i = 0;
int cityProbability = 0;
for (auto it = vec.begin() ; it != vec.end() ; ++it)
{
cityProbability = *it;
if ((i + cityProbability) > nbReference)
{
return (i + 1);
}
i += cityProbability;
}
First i create a number equals to the addition of all city's probability
int nbReference = 0;
for (auto it = vec.begin() ; it != vec.end() ; ++it)
{
nbReference += *it;
}
Second, i generate a number that is respect the following range -> 0 < nbReference
Third, i create a loop that take all city one by one and quit when we got right city.
How does we know when a city is good?
Let's take an example!
With our previous probability
5 3 8 5 12 14 8 5 6 18
NbReference is equals to (5+3+8+5+12+14+8+5+6+18) so 84
To each city we are going to put a range equals to his probability plus all of previous city's probability. Let me show you :
5 -> Range 0 to 4 (0 to 4 = 5 ---> 5%)
3 -> Range 5 to 8 (5 to 8 = 3 ---> 3%)
8 -> Range 9 to 17
5 -> Range 18 to 22
... etc
If the number that we create here
nbReference = rand(nbReference);
Is in a city range, so that city is choosed.
Example : If the number is 16, city3 is choosed!
5 -> Range 0 to 4 Number is 16 so NOPE
3 -> Range 5 to 8 Number is 16 so NOPE
8 -> Range 9 to 17 Number is 16 so YES!
5 -> Range 18 to 22
... etc
Does is this helpfull? :)
Any questions? You are welcome
Maybe this code can help you (follows partially WhozCraig advice)
#include <iostream>
#include <random>
#include <algorithm>
int main(int argc, const char * argv[])
{
using namespace std::chrono;
system_clock::time_point tp = system_clock::now();
system_clock::duration dtn = tp.time_since_epoch();
std::default_random_engine generator(static_cast<int>(dtn.count()));
//Generate 34 cities
std::uniform_real_distribution<double> gen_distribution(0,1);
auto getProb = std::bind ( gen_distribution, generator );
std::vector<double> citiesProb;
double probSum(0.0);
double cityProb(0.0);
for (int k=0; k < 34; k++)
{
cityProb = getProb();
probSum += cityProb;
citiesProb.push_back(cityProb);
}
//Pick 7 cities
std::uniform_real_distribution<double> pick_distribution(0,probSum);
auto pickCity = std::bind ( pick_distribution, generator );
double chooseCity;
double probBasket;
for (int k=0; k < 7; ++k)
{
probBasket = 0.0;
chooseCity = pickCity();
for (int i = 0; i < citiesProb.size(); ++i)
{
if (chooseCity >= probBasket && chooseCity < probBasket + citiesProb[i])
{
std::cout << "City with index " << i << " picked" << std::endl;
}
probBasket += citiesProb[i];
}
}
return 0;
}
How it works:
city1 5%(0.05), city2 25%(0.25), city3 8%(0.08), city4 10%(0.1)
then
probSum = 0.05 + 0.25 + 0.08 + 0.1 = 0.48
then choose a number between 0 and 0.48 (named pickProb) and
if pickProb is between 0 and 0.05 pick city1 (prob = 0.05/0.48 = 10%)
if pickProb is between 0.05 and 0.30 pick city2 (prob = 0.25/0.48 = 52%)
if pickProb is between 0.30 and 0.38 pick city3 (prob = 0.08/0.48 = 16%)
if pickProb is between 0.38 and 0.48 pick city4 (prob = 0.1/0.48 = 20%)
if probSum = 1.0 then city1 is picked with probability 5%, city2 is picked with probability 25% and so on.

C++ Using “if else” and variable count for loop iterations need to result in zero balance

I am using the “if else” and variable count for loop iterations which needs to result in zero balance. I have written my code for the following problem but, I cannot get the final results.
Which is the final balance should show a zero balance. I would like to know how to fix it.
Please see problem and code below.
Thank You in Advance.
PROBLEM You have just purchased a
stereo system that costs $2,000 on the
following credit plan: no down
payment, an interest rate of 18% per
year (and hence 1.5% per month) and
monthly payments of $75.
The monthly payment of $75 is used to
pay the interest and whatever is left
over is used to pay part of the
remaining debt. Hence, the first month
you pay 1.5% of $2,000 in interest .
That’s $30 in interest. So, the
remaining $45 is deducted from your
debt, which leaves you with a debt of
$1955.00. The next month you pay
interest of 1.5% of $1955.00, which is
$29.32 and you deduct $75 - $29.32
which is $45.67 from the amount you
owe.
Have your program print out the month,
the amount of interest paid, and the
amount of the debt that is paid and
the debt that remains in a nice table
form. Make sure to include a line in
the table for the final month that you
pay. Your remaining debt should be
zero for that line! Be sure to print
money out to 2 decimal places, as
shown below.
Sample output:
Thank you for purchasing your new stereo system.
The following is your payment plan for the cost of $2000.00
with 1.50% interest and payments of $75.00 a month.
Month Interest Paid Debt Paid Total Payment Balance
1 30.00 45.00 75.00 1955.00
2 29.32 45.67 75.00 1909.33
3 28.64 46.36 75.00 1862.96
4 27.94 47.06 75.00 1815.91
5 27.24 47.76 75.00 1768.15
6 26.52 48.48 75.00 1719.67
7 25.80 49.20 75.00 1670.47
8 25.06 49.94 75.00 1620.52
9 24.31 50.69 75.00 1569.83
10 23.55 51.45 75.00 1518.38
11 22.78 52.22 75.00 1466.15
12 21.99 53.01 75.00 1413.15
13 21.20 53.80 75.00 1359.34
14 20.39 54.61 75.00 1304.73
15 19.57 55.43 75.00 1249.30
16 18.74 56.26 75.00 1193.04
17 17.90 57.10 75.00 1135.94
18 17.04 57.96 75.00 1077.98
19 16.17 58.83 75.00 1019.15
20 15.29 59.71 75.00 959.43
21 14.39 60.61 75.00 898.83
22 13.48 61.52 75.00 837.31
23 12.56 62.44 75.00 774.87
24 11.62 63.38 75.00 711.49
25 10.67 64.33 75.00 647.16
26 9.71 65.29 75.00 581.87
27 8.73 66.27 75.00 515.60
28 7.73 67.27 75.00 448.33
29 6.73 68.27 75.00 380.06
30 5.70 69.30 75.00 310.76
31 4.66 70.34 75.00 240.42
32 3.61 71.39 75.00 169.03
33 2.54 72.46 75.00 96.56
34 1.45 73.55 75.00 23.01
35 0.35 23.01 23.36 0.00
Note that the last payment is $23.36,
Hints: Use a variable to count the number of loop iterations and hence the number of months until the debt is zero.
Be careful, the last payment may be less than $75.
Also, don’t forget the interest on the last payment. If you owe $75,then your monthly payment of $75 will not pay it off, but will come close.
Make sure you look carefully at your final output to check that it is correct!
MY CODE
#include<iostream>
#include<string>
using namespace std;
int main()
{
float balance;
float interest;
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
double loan, monthlypay, IntRat;
double e = 0;
double a, b, c, d;
double Interestpay;
double i;
cout << "Enter the amount of the loan: $";
cin >> loan;
cout << "Enter the interst per year:";
cin >> Interestpay;
cout << "Enter the monthly pay: $";
cin >> monthlypay;
c = loan;
cout << endl;
cout << endl;
cout << endl;
for ( i=1; c>0; i++)
{
IntRat = Interestpay/100/12;
a = IntRat*c;
b = monthlypay-a;
cout << "Month: "<<i<<endl;
cout << "Principle Interest:" <<a<<endl;
cout << "Principle Remaining: $" <<b<<endl;
c = c-b;
cout << "You still have a balance of: $" <<c<<endl;
cout << endl;
d=e+a;
e=d;
}
i=i-1;
if (c >=b)
c = c -b;
else if (c>0.1)
c=c*1;
c = 0;
cout << "Your last payment is " << c << endl;
cout << "\nThe total month is:" <<i<<endl;
cout << "The total Interest paid is:" <<d<<endl;
cout << "You have a credit of:" <<c<<endl;
return 0;
}
It is generally not recommended to use floating-point types to represent currency amounts. It's typically better to use "fixed point". A simple way of doing that is to e.g. use an integer type such as int, and just scale up.
Instead of doing
double monthlyPayment = 75.0;
use
int montlyPayment = 7500;
Then you need to divide by 102 if you e.g. multiply two currency amounts together, and so on, but doing it this way can often make the calculations more exact (unless you go out of range, but for this simple example I think you'll be safe).
If you need more precision, scale by a larger amount such as 10000, but be aware that doing so decreases the range.
From a fast look, maybe you mean :
i=i-1;
if (c >=b)
{
c = c -b;
}else if (c>0.1)
{
c=c*1;
c = 0;
}
In your code c = 0; is executed irrespectively of the if clause. If that is not the case please fix your code indent.
In case you mean what I post in this answer, you realize that c will be 0 ? In the case your code is what you meant, you realize that no matter what c will be 0 ?