+ 1I有一个2D数组,我需要计算平均值/平均值和方差。问题是,当我这样做时,我得到的数字比我应该大。 IE:我的2D数组中的最大值是256,但最终平均值高达303.
因此,很明显我正在计算均值和方差。谁能告诉我这里哪里出错?代码完全在下面。
如果您想尝试编译并查看结果,以下是其中一个文件:http://shawndibble.com/baboon.pgma
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const int THRESHOLD = 2048; //random threshold variable to determine when to replace a row.
void optimizeImage(int (*imageFile)[512], int mincol, int maxcol, int row) {
int sum, average;
double temp, variance, elements;
elements = (maxcol-mincol+1)*row;
if(mincol != maxcol) { // if maxcol and mincol are the same. We are on a single row & don't need to do anything.
// Figure out average
for (int i = mincol; i < maxcol; i++) {
for (int j = 0; j < row; j++) {
sum += imageFile[i][j];
}
}
average = sum / elements;
// figure out variance
for (int i = mincol; i < maxcol; i++) {
for (int j = 0; j < row; j++) {
temp += (imageFile[i][j] - average) * (imageFile[i][j] - average);
}
}
variance = temp / elements; //calculate variance
//cout << "var: " << variance << " thresh: " << THRESHOLD << endl;
cout << "rows : " << maxcol-mincol+1 << " | average: " << average << endl;
// if threshold is higher than variance, replace entire row with average
if(THRESHOLD >= variance) {
for(int i = mincol; i < maxcol; i++) { // if quad variance is < THRESHOLD, write whole quad to output array
for (int j = 0; j < row; j++) {
imageFile[i][j] = average;
}
}
cout << "run average" << endl;
// otherwise break in half and repeat.
} else {
int mid = ((maxcol+mincol)/2) ;
optimizeImage(imageFile, mincol, mid, row);
optimizeImage(imageFile, mid+1 , maxcol, row);
}
}
}
int main() {
ifstream inFile;
inFile.open ("baboon.pgma");
if (!inFile) {
cout << inFile << " is a not working for me.";
} else {
//time to read the file,
string line1, line2;
int row, col, maxval;
getline (inFile, line1);
getline (inFile, line2);
inFile >> row;
inFile >> col;
inFile >> maxval;
int imageFile [512][512];
// read each integer and place it into a 2D array
for (int i=0; i < col ; i++) {
for (int j=0; j<row; j++){
inFile >> imageFile[i][j];
}
}
inFile.close();
ofstream dataOut;
dataOut.open ("BaboonOptimized.pgma");
dataOut << line1 << endl << line2 << endl << row << " " << col << endl << maxval << endl;
optimizeImage(imageFile, 0, col, row);
for (int i=0; i < col ; i++) {
for (int j=0; j<row; j++){
dataOut << imageFile[i][j] << " ";
}
}
dataOut.close();
}
return 0;
};
答案 0 :(得分:0)
您尚未初始化sum
和temp
。