我是一名自學成才的 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
歡迎對問題和備注或代碼格式提供任何幫助。
uj5u.com熱心網友回復:
您呼叫AverageSurroundingswithrow==0和/或col==0(請參閱 中的回圈變數Average)。
但是std::size_t是UNSIGNED型別...所以當它為零時,負 1,它在AverageSurroundings's 回圈中下溢并回傳0xFFFF FFFF FFFF FFFF...這顯然大于row 1(或col 1)。所以回圈不會執行一次。
即使沒有下溢,即使使用適當的“-1”作為索引,您仍然會在矩陣之外...
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/447091.html
