Good morning. I have written a homework solution that seems to be what is required however, I am getting an error message that states, "Vector subscript is out of range". Can you tell me what this means and where in my code to start looking to fix it? Thanks.
#include <iostream>
#include <vector>
#include <string>
#include <iomanip>
usingnamespace std;
int main()
{
float d,a, average=0, minimum=0, balance=1143.24;
float balance2=1143.24;
float min_interest=0, avg_interest=0;
string s;
int j=0;
bool b=true;
// Declares three vectors to store the day, amount and a description of the entry
vector <int> day;
vector <float> amount;
vector <string> description;
// store the intial entry in a vector
day.push_back(1);
amount.push_back(1143.24);
description.push_back("Initial Balance");
cout << "Press 0 to stop input \n";
cout << "Enter your input in form: day, amount and description \n";
// While loop to store user input while user does not select 0 for day.
while (b)
{
cin >> d;
if(d==0)
{
b=false;
}
else
{
cin >> a;
getline(cin, s);
day.push_back(d);
amount.push_back(a);
description.push_back(s);
}
}
cout << "";
cout << "Day \t\ Amount \t Description \t\t Balance \n";
//For loop will show the entryies and calculate minimum and average balance by day
for(int i=0; i<30; i++)
{
if(i+1==day[j])
{
if(j!=0)
{
balance=balance+amount[j];
}
if (balance2 > balance);
{
balance2 = balance;
}
// Prints output on the screen
cout << day[j] << "\t" << amount [j] << "\t\t" << description[j] <<
"\t\t" << balance << "\n";
j++;
}
// calculates the average daily balance based on 30 day month
average = average + balance;
// calculates the minimum daily balance based on 30 day month
minimum = minimum + balance2;
balance2 = balance;
}
// calculates the rate of interest
float apr=0.5/100;
// calculates 30 cycle to find minimum and average daily balances
float cycle =(float)30/365;
// calculates average and minimum daily interest
min_interest=apr*cycle*minimum;
avg_interest=apr*cycle*average;
cout << "";
//display average and minimum daily balance interest
cout << "Interest according to your minimum daily balance is: " << min_interest << "\n";
cout << "Interest according to your average daily balance: " << avg_interest << "\n";
system ("PAUSE");
return 0;
}
Being out of range, in your case, means that at some point j has a higher value than it should, and tries to access an element that doesn't exist.
For instance suppose that day has 5 elements.
Then at some point j becomes 10. day[10] has its index out of range, it should be from 0 to 4, including.
Suggestions: 1) Print j and day.size() to see what happens. 2) Take a look at line 50, the hardcoded value 30 stands out. That is called a "magic number".