anxn 行列を与えるベクトルのベクトルがあります。for ループを使用してマトリックス内のすべての要素を合計すると、奇妙な結果が得られます。
関連するコードは次のとおりです。
int main(){
while(cin){
int n = 0;
int sum = 0;
cout << "\n\nEnter a size (n) for the matrix: ";
cin >> n;
vector<vector<int> > matrix ( n, vector<int> ( n ) );
int k = 0;
for ( int i = 0; i < n; i++ ) {
for ( int j = 0; j < n; j++ )
matrix[i][j] = k++;
}
for ( int i = 0; i < n; i++ ) {
for ( int j = 0; j < n; j++ )
cout<< setw ( 3 ) << matrix[i][j] <<' ';
cout<<'\n';
}
for ( int i = 0; i < n; i++ ) {
for ( int j = 0; j < n; j++ )
sum += matrix[i][j];
}
cout << "\nThe sum of the elements of the matrix is: " << sum << ' \n';
}
}
それで、奇妙なのは...「合計」の値を出力すると、何らかの理由で、値に「8202」が追加されることです。n = 1 を指定すると 08202 が出力され、n of 3 の場合は 368202 が出力されます。
何か案は?Code::Blocks でデバッガーを試しましたが、成功しませんでした。