【发布时间】:2019-09-25 16:20:54
【问题描述】:
对于这个作业问题,我们需要使用教授提供的代码创建一个新的锯齿状数组,打印数组,并计算数组内容的最大值、最小值和总和。我们只允许编辑 createAndReturnJaggedArray() 和 printAndThenFindMaxMinSum(int**,int*,int*,int*) 函数,因为其余代码是为我们提供的,因此我们可以检查是否得到正确的输出。
我能够让程序运行,但是在打印初始字符串后,它会终止程序,给我错误terminate called after throwing an instance of 'std::bad_array_new_length' what(): std::bad_array_new_length。我相信问题在于我创建了锯齿状数组以及我为数组的列部分分配了内存,但是我使用了我们提供的注释作为参考并且不知道问题出在哪里。下面提供了整个程序。感谢您的帮助!
编辑/注意:我们还没有学过向量,所以我们不能使用它们。
#include <iostream>
#include <climits>
using namespace std;
class JaggedArray {
public:
int numRows;
int *numColumnsInEachRow;
JaggedArray() {
numRows = 11;
numColumnsInEachRow = new int[numRows];
for (int i = 0; i < numRows; i++) {
if (i <= numRows / 2) {
numColumnsInEachRow[i] = i + 1;
} else {
numColumnsInEachRow[i] = numRows - i;
}
}
readComputeWrite();
}
int **createAndReturnJaggedArray() { // COMPLETE THIS FUNCTION
int **A = new int*[numRows];
for(int i=0;i<numRows;i++){ //allocate columns in each row
A[i] = new int[numColumnsInEachRow[i]];
for(int j=0;j<numColumnsInEachRow[i];j++){
if(i <= numRows/2)
A[i][j] = (i + j);
else
A[i][j] = -1 * (i+j);
}
}
return A;
}
void printAndThenFindMinMaxSum(int **A, int *maxPtr, int *minPtr, int *sumPtr) { // COMPLETE THIS FUNCTION
maxPtr = new int[INT_MIN];
minPtr = new int[INT_MAX];
sumPtr = 0;
for(int i=0;i<numRows;i++){
for(int j=0;j<numColumnsInEachRow[i];j++){
//1. print array
if (j == (numColumnsInEachRow[i]-1))
cout << A[i][j] << endl;
else
cout << A[i][j] << " ";
//2. compute max, min, and sum
sumPtr += A[i][j];
if (A[i][j] > *maxPtr)
maxPtr = new int[A[i][j]];
if (A[i][j] < *minPtr)
minPtr = new int[A[i][j]];
}
}
}
void print(int max, int min, int sum) {
cout << endl;
cout << "Max is " << max << "\n";
cout << "Min is " << min << "\n";
cout << "Sum is " << sum << "\n";
}
void readComputeWrite() {
int max, min, sum;
int **A = createAndReturnJaggedArray();
cout << "*** Jagged Array ***" << endl;
printAndThenFindMinMaxSum(A, &max, &min, &sum);
print(max, min, sum);
}
};
int main() {
JaggedArray jaf;
return 0;
}
【问题讨论】:
-
@Joseph Wood 是的,我们还没有学习矢量,因此不允许使用它们。 :\
-
@JosephWood 好电话,会的
-
maxPtr = new int[INT_MIN];在我看来有点问题。不知道你在这里做什么,但INT_MIN是一个大的负数。数组和负数不能混用。minPtr = new int[INT_MAX];是可能的,但可能需要 18 万亿字节的 RAM。祝你好运。 9万亿,对不起。蓝精灵。我出去了。 9 quintillion 字节。反正很多内存。 -
@user4581301 是的,这是有道理的。在作业指导中,我们的老师建议将
maxPtr初始化为INT_MIN,将minPtr初始化为INT_MAX,并将sumPtr初始化为0。有没有更好的写法这样它不会溢出程序? -
阅读更多。在计算 min 和 max 时,通常每个只需要一个数字。例如,要获取数组中的最大值,您只需要存储到目前为止您见过的最大数字,以及最小的最小值。平均而言,您需要两个变量:到目前为止您看到的所有数字的总和(获取一个 BIG 数据类型来存储它)和您总结的数字的数量。
标签: c++ pointers jagged-arrays