2016-02-09 3 views
0

Я начал работать с динамической памятью, а во время работы программы она рушилась. Мой ввод - 26 платежей и вывод в файл .csv, где номер платежа - 25, причина ошибки в программной памяти. Недопустимая память. (Извините за мой плохой английский, я думаю, вы понимаете, что я имею в виду).Во время работы, сбой программы (Codeblock C++)

#include <iostream> 
#include <fstream> 
#include <iomanip> 
#include <cmath> 
using namespace std; 

int main() 
{ 
     int year, month, day, payments; 
     float total, presentValue, interestRate; 
     float *Remaining, *Principal, *Interest; 
     cout << "Insert date" << endl; 
     cin >> year >> month >> day; 
     cout << "Insert Present Value" << endl; 
     cin >> presentValue; 
     cout << "Insert Interest Rate" << endl; 
     cin >> interestRate; 
     cout << "Insert number of payments" << endl; 
     cin >> payments; 
     Remaining = new(nothrow)float[payments]; 
     Principal = new(nothrow)float[payments]; 
     Interest = new(nothrow)float[payments]; 
     Remaining[0] = presentValue; 
     total = (Remaining[0] * (interestRate/1200))/(1 - pow(1 + (interestRate/1200), payments*(-1))); 
     cout << total; 
     ofstream myfile; 
     myfile.open ("payments3.csv"); 
     myfile << "Payment #;Payment date;Remaining amount; \ 
     Principal payment;Interest payment;Total payment;Interest rate" << endl; 
     for (int i = 0; i < payments; i++) { 
      myfile << i+1 << ";"; 
      if (month > 12) { 
       month = 1; 
       year += 1; 
      } 
      myfile << year << '-' 
      << month << '-' 
      << day 
      << ";"; 
      month++; 
      Interest[i] = Remaining[i] * (interestRate/1200); 
      Principal[i] = total - Interest[i]; 
      Remaining[i+1] = Remaining[i] - Principal[i]; 
      myfile << fixed << showpoint; 
      myfile << setprecision(2); 
      myfile << Remaining[i] << ";" << Principal[i] << ";" << Interest[i] << ";\ 
      " << total << ";" << interestRate << endl; 
     } 
     myfile.close(); 
     delete[] Remaining; 
     delete[] Principal; 
     delete[] Interest; 
     return 0; 
} 

ответ

0

хорошо, следующая строка пытается получить доступ из диапазона:

Remaining[i+1] = Remaining[i] - Principal[i]; 

попробовать это:

if (i + 1 < payments) 
    Remaining[i+1] = Remaining[i] - Principal[i]; 
+0

Спасибо, что работает –

0

используется Remaining[0] и Remaining[i+1] специально, что, вероятно, означает, что вам нужен один дополнительный элемент этого массива.

В противном случае [i+1] будет находиться вне границ во время последнего поворота в цикле.

Смежные вопросы