简体   繁体   English

运行时,程序崩溃(代码块C ++)

[英]While running, crashing program (Codeblock C++)

I started work with dynamic memory, and while program running it's crashing. 我开始使用动态内存,而程序运行时却崩溃了。 My input is 26 payments, and output to .csv file where payments number is 25 cause program crashing nad allocated memory is wrong (Sorry for my bad english, I guess you understand what i meaning). 我的输入是26付款,并输出到付款编号为25的.csv文件,导致程序崩溃且分配的内存错误(对不起,我的英语不好,我想您明白我的意思)。

#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;
}

You use Remaining[0] and Remaining[i+1] specially, which probably means that you need one extra element of that array. 专门使用Remaining[0]Remaining[i+1] ,这可能意味着您需要该数组的一个额外元素。

Otherwise the [i+1] will be out of bounds during the last turn in the loop. 否则, [i+1]在循环的最后一圈将超出范围。

well, the following line tries to access out of range: 好吧,以下行尝试访问超出范围的内容:

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

try this: 尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM