Modify this code so that the interest rate is read from a file called rate.dat.
ID: 3634060 • Letter: M
Question
Modify this code so that the interest rate is read from a file called rate.dat. Where must the file be located? Try writing a file from the program and then searching for it.#include<iostream>
#include<iomanip>
using namespace std;
int main(int argc, char * argv[])
{
//variable initialization
double rate=0.05;//
double bal=100;
double interest;
double totalInterest=0;
cout<<"YEAR Interest Balance Total Interest ";
//Running for loop for ten times
for(int i=0;i<10;i++)
{
//compound interest calculation
//find interest
interest=bal*rate;
//adding interset to balance
bal=bal+interest;
//adding interest to find total interst
totalInterest+=interest;
cout<<i+1<<" "<<interest<<" "<<bal<<" "<<totalInterest<<endl;
}
cout<<"Total Interest for Ten years:"<<totalInterest<<endl;
system("pause");
return 0;
}
Thank you very much in advance. :))
Explanation / Answer
please rate - thanks
make sure the input file is created with the extension .dat and not .txt, and is in the same directory as the code
save as "rate.dat" include the quotes.
the output now goes to a file named output.txt
and is nicer
#include<iostream>
#include<iomanip>
#include <fstream>
using namespace std;
int main(int argc, char * argv[])
{
//variable initialization
double rate=0.05;//
double bal=100;
double interest;
double totalInterest=0;
ifstream in;
ofstream out;
in.open("rate.dat");
if(in.fail())
{ cout<<"input file did not open please check it ";
system("pause");
return 1;
}
out.open("output.txt");
in>>rate;
out<<"YEAR Interest Balance Total Interest ";
//Running for loop for ten times
for(int i=0;i<10;i++)
{
//compound interest calculation
//find interest
interest=bal*rate;
//adding interset to balance
bal=bal+interest;
//adding interest to find total interst
totalInterest+=interest;
cout<<setprecision(2)<<fixed;
out<<i+1<<" "<<setprecision(2)<<fixed<<interest<<" "<<
setprecision(2)<<fixed<<bal<<" "
<<setprecision(2)<<fixed<<totalInterest<<endl;
}
out<<"Total Interest for Ten years: $"<<setprecision(2)<<fixed<<totalInterest<<endl;
cout<<"Program complete ";
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.