【问题标题】:Comparison is always false due to limited range of data type trying to saturate colors由于试图使颜色饱和的数据类型范围有限,比较总是错误的
【发布时间】:2016-04-15 23:32:47
【问题描述】:

我正在尝试使颜色饱和并确保它们不会溢出 这样他们就可以绘制出漂亮的 Mandlebrot 集而不会被像素化。 我正在使用 Altera DE2 板尝试通过 VGA 连接将这个 Mandlebrot 集打印到计算机屏幕上,颜色略有偏差(像素)。

我该如何更正下面代码中的 if 语句不总是错误的?

if (iteration == 500)
{
    alt_up_pixel_buffer_dma_draw(my_pixel_buffer,0,0,0);
}
else
{
    //double z = sqrt(xtemp * xtemp + y * y);
    //int brightness = 256. * log2(1.75 + i - log2(log2(z))) / log2(500);
    //color(brightness, brightness, 255);
    //color is some function of iteration
    alt_u8 Red = (iteration*8);///zoom);
    if(Red > 255) // this if statement is always false
        Red = 255;

    alt_u8 Green = (iteration*4);///zoom);
    if(Green > 255) // this if statement is always false
        Green = 255;

    alt_u8 Blue = (iteration*2);///zoom);
    if(Blue > 255) // this if statement is always false
        Blue = 255;

    //draw the pixels
    alt_up_pixel_buffer_dma_draw(my_pixel_buffer, (Blue) + (Green<<8) + (Red<<16),j,i);
}

【问题讨论】:

  • 你忘了问问题。
  • 对不起,谢谢。我希望了解为什么或如何修复代码中的 if 语句以不总是产生错误

标签: c colors warnings compiler-warnings mandelbrot


【解决方案1】:

你需要用一个更大的整数来得到相乘的结果,这样你就可以测试它是否超过了限制。

alt_u8 Red;
uint16_t tempRed = iteration * 8;
if (tempRed > 255) {
    Red = 255;
} else {
    Red = tempRed;
}

【讨论】:

    【解决方案2】:

    由于alt_u8 中可以存储的最大值是 255,因此检查它是否包含更大的值是没有意义的。 (如果不是这种情况,您将不会收到警告,即使 alt_u8 的类型不可见。)

    但是,这也意味着您的分配很危险,因为分配的值是以 256 为模存储的。您可能需要使用:

    alt_u32 new_Red = iteration * 8;  // Guessed type; uint32_t or uint16_t would do
    alt_u8 Red = new_Red;
    if (new_Red > 255)
        Red = 255;
    

    现在new_Red 中的值可以超过 255,但分配确保存储饱和值,而不是 new_Red % 256,否则会存储。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-09
      • 1970-01-01
      • 2018-01-01
      • 2015-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-14
      相关资源
      最近更新 更多