[英]C - Floating Point Exception (core dumped)
該功能應該通過將每個像素的顏色按2n + 1個“半徑”的平均值轉換為每個像素的顏色來使圖像模糊。
(不必擔心跳到下一個像素的部分)。
我成功地編譯了這段代碼:
void
blur_pixels(image *img, pixel *p, size_t i, size_t j)
{
//i = current height of pixel, j = current width of pixel
int side = 2*blurRate+1;
int total = 0;
int leftRight = i-blurRate;
int upDown = j-blurRate;
int tmpHr = 0, tmpHg = 0, tmpHb = 0;
for(; upDown < j+blurRate; upDown++) {
if(upDown >= 0 && upDown < img->height) {
for(; leftRight < i+blurRate; leftRight++) {
if(leftRight >= 0 && leftRight < img->width) {
tmpHr += (p+leftRight)->r;
tmpHg += (p+leftRight)->g;
tmpHb += (p+leftRight)->b;
total++;
}
}
}
}
p->r=tmpHr/total;
p->g=tmpHg/total;
p->b=tmpHb/total;
}
但是,當我運行代碼時,出現以下異常:
Floating point exception
有人知道為什么嗎?
代碼用p->r=tmpHr/total;
進行0 p->r=tmpHr/total;
total
可能為零,因為未打開編譯器警告以顯示for()
循環的混合有符號/無符號數學。 打開所有編譯器警告。
比較upDown < j+blurRate
和其他代碼是使用無符號數學完成的,可能不像OP期望的那樣,也不是內部total++;
永遠不會發生。 如果upDown < 0
,則upDown
upDown < j+blurRate
變為一個大的無符號值。 然后比較是假的。
size_t j // an unsigned type
...
int upDown = j-blurRate;
...
for(; upDown < j+blurRate; upDown++) { // not firing
一種解決方案是僅使用int
變量。 一個更健壯的解決方案將使用無符號數學,但要獲得一個好的答案,還需要更多的高級代碼。
就像是:
blur_pixels(image *img, pixel *p, size_t i, size_t j) {
//i = current height of pixel, j = current width of pixel
size_t side = 2u*blurRate+1;
size_t total = 0;
size_t leftRight = (i > blurRate) ? i-blurRate : 0;
size_t upDown = (j > blurRate) ? j-blurRate : 0;
int tmpHr = 0, tmpHg = 0, tmpHb = 0;
for(; upDown < j+blurRate; upDown++) {
if (upDown < img->height) {
// I suspect leftRight needs to be set here each iteration
size_t leftRight = (i > blurRate) ? i-blurRate : 0;
for(; leftRight < i+blurRate; leftRight++) {
if (leftRight < img->width) {
tmpHr += (p+leftRight)->r;
tmpHg += (p+leftRight)->g;
tmpHb += (p+leftRight)->b;
total++;
}
}
}
}
if (total) {
p->r = tmpHr/total;
p->g = tmpHg/total;
p->b = tmpHb/total;
} else {
p->r = p->g = p->b = 0;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.