gpt4 book ai didi

c++ - 阵列周围的堆栈已损坏

转载 作者:行者123 更新时间:2023-11-28 02:12:06 25 4
gpt4 key购买 nike

我使用的是 Visual Studios 2015,但遇到了问题。运行时检查失败 #2 - 变量“myArray”周围的堆栈已损坏。我不确定程序中的哪个位置可能会导致我的阵列出现某种损坏。但是当我进行涉及操纵数组的计算时,有几个数字变成了 0.0000 而不是它们原来的样子。有人可以帮忙吗?

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

int main()
{
double xmin, xmax;
const int POINTS = 20;
const double PI = 3.1416;
double increments;
double range, mean;
double total = 0;
double myArray[POINTS];
double number = myArray[0];
double mode = number;
int count = 1;
int countMode = 1;

cout << "Enter in a value for the minimum x value: ";
cin >> xmin;
cout << "Enter in a value for the maximum x value: ";
cin >> xmax;

if (xmin < 0)
increments = (abs(xmin) + xmax) / POINTS;
else
increments = (xmax - xmin) / POINTS;

int i = 0;
double x = xmin + increments * i;
double minimum = 0.0572 * cos(4.667 * x) + 0.0218 * PI * cos(12.22 * x);
double maximum = myArray[19];

cout << setw(15) << "x |" << setw(15) << "f(x)" << endl;
cout << setw(32) << setfill('-') << " " << endl;
cout << setfill(' ');

for (i = 0; i <= POINTS; i++)
{
myArray[i] = 0.0572 * cos(4.667 * x) + 0.0218 * PI * cos(12.22 * x);
x = xmin + increments * i;
cout << fixed << showpos << setw(15) << setprecision(2) << x << setw(15) << setprecision(4) << myArray[i] << endl;

if (myArray[i] <= minimum)
minimum = myArray[i];
if (myArray[i] > maximum)
maximum = myArray[i];
}

cout << endl;
range = maximum - minimum;
for (int count = 0; count <= POINTS; count++)
{
total += myArray[count];
}
mean = total / POINTS;

int temp;
bool swap;
do
{
swap = false;
for (int i = 0; i < POINTS - 1; i++)
{
if (myArray[i] > myArray[i + 1])
{
temp = myArray[i];
myArray[i] = myArray[i + 1];
myArray[i + 1] = temp;
swap = true;
}
}
} while (swap);


for (int i = 0; i <= POINTS; i++)
{
if (myArray[i] == number)
{
count++;
}
else
{
if (count > countMode)
{
countMode = count;
mode = number;
}
count = 1;
number = myArray[i];
}
}

cout << "The maximum value is: " << maximum << endl;
cout << "The minimum value is: " << minimum << endl;
cout << "The range is: " << range << endl;
cout << "The mean value is: " << mean << endl;
cout << "The median value is: " << (myArray[9] + myArray[10]) / 2 << endl;
cout << "The mode value is: " << mode << endl;

for (i = 0; i <= POINTS; i++)
cout << myArray[i] << endl;

system("pause");
return 0;
}

最佳答案

double myArray[POINTS];

myArray 是一个包含 20 个 double 的数组 - myArray[0]myArray[19]

for (i = 0; i <= POINTS; i++)
{
myArray[i] = 0.0572 * cos(4.667 * x) + 0.0218 * PI * cos(12.22 * x);

这会设置 myArray[0]myArray[20]。不允许访问 myArray[20],因为它是 20 元素数组的第 21 个元素。

请注意,编译器不会总是很好地为您检测到这个问题。信不信由你,Visual C++ 通过导致程序崩溃来帮您一个忙。

关于c++ - 阵列周围的堆栈已损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35283771/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com