for循环未在零参数上执行



我是一个自学成才的python&C程序员和我正在努力学习C++

作为一个小练习,我试图移植我在Python迷你游戏中创建的一个函数,该函数生成一个随机矩阵,然后对其求平均值,以创建一个具有地形高程的地图。

我尝试在C++中使用size_t和数组最大大小的技巧来实现它,我以前已经在C中成功地使用过它。

然而,当在第0行或第0列上运行时,我的AverageSurroundings中的for循环似乎不会运行。stderr上的输出证实了这一点(对不起,我不知道如何回答这个问题(,并导致除以零的错误,这是不应该发生的。我已经做了一个小的修复,但我找不到问题的根源

下面是一个显示问题的小片段。

#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/assignment.hpp> //for <<= 
#include <cstdint>
#include <iostream>
static const std::size_t n_rows = 3;
static unsigned int
AverageSurroundings(const boost::numeric::ublas::matrix<unsigned int> mat,
const std::size_t row, const std::size_t col) {
std::uint_fast16_t sum = 0; // <= 9*255= 2295 => 12 bits
std::uint_fast8_t count = 0;
std::cerr << "AverageSurroundings(" << row << ',' << col << ") called." << 'n';
for ( std::size_t r = row - 1; r <= row + 1; r++) {
for (std::size_t c = col - 1; c <= col + 1; c++) { // these values should remain positive, so we just 
// need to check if we are smaller than n_rows, 
//thanks to the wraparound of size_t.
std::cerr<<"r:"<<r<<" c:"<<c<<'n'; // FIXME : loop not executing on first row/column
if (r < n_rows && c < n_rows) {
sum += mat(r, c);
count++;
std::cerr << "AverageSurroundings(" << row << ',' << col << "): Neighbour found at (" << r<< ',' << c << ")." <<'n';
}
}
}
std::cerr << std::endl; // flushing and adding a blank line.
return count ? static_cast<unsigned int>(sum / count):0; //  count is 8bits long so no overflow is possible, casting to silence warning.
//added ? to avoid floating point error for debug. FIXME : This should NOT BE 0   
}
static const boost::numeric::ublas::matrix<unsigned int>
Average(const boost::numeric::ublas::matrix<unsigned int> mat,
const std::size_t rows) {
using boost::numeric::ublas::matrix;
matrix<unsigned int> m(n_rows, n_rows);
for (std::size_t row = 0; row < rows; row++) {
for (std::size_t col = 0; col < rows; col++) {
m(row, col) = AverageSurroundings(mat, row, col);
std::cout << m(row, col) << 't';
}
std::cout << 'n';
}
std::cout << std::endl;
return m;
}
int main() {
using boost::numeric::ublas::matrix;
matrix<unsigned int> m(n_rows,n_rows); m <<=  0, 1, 2,
3, 4, 5,
6, 7, 8;
std::cout<< "---- RESULT ----" << 'n'; 
const matrix<unsigned int> m2 = Average(m, n_rows);
}

以及相应的输出。

---- RESULT ----
0   0   0   
0   4   4   
0   5   6   

欢迎提供有关该问题的任何帮助以及备注或代码格式。

使用row==0和/或col==0调用AverageSurroundings(请参阅Average中的循环变量(。

std::size_t是一个UNSIGNED类型。。。因此,当它为零减1时,它在AverageSurroundings的循环中下溢并返回0xFFFF FFFF FFFF FFFF。。。明显大于row+1(或col+1(。所以循环一次也不执行。

即使没有下溢,即使使用适当的"-1〃;作为索引。。。

最新更新