0
+1 평균/평균 및 분산을 계산해야하는 2D 배열이 있습니다. 문제는 내가 할 때, 나는 내가해야하는 것보다 더 큰 숫자를 얻는다는 것이다. IE : 2D 배열의 최대 값은 256이지만 최대 303 개의 평균값을 얻을 수 있습니다.2 차원 배열이있는 C++의 평균 및 분산
이와 같이 평균과 분산을 잘못 계산하고있는 것은 분명합니다. 누군가 내가 여기서 잘못 가고 있다고 말할 수 있습니까? 아래 코드를 모두 작성하십시오. 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;
};
당신은'sum'과'temp'를 초기화하지 않았습니다. 나머지 이유를 확인하는 이유 중 하나가 될 수 있습니다. –
감사합니다. 그거였다. 이러한 변수를 초기화하고 나면 모든 것이 나오게되었습니다. –