c++ - 除以 0 警告

标签 c++ visual-studio-2012

我一直在处理一个应用程序,因为图像表现得很奇怪,所以我决定打开 Wall 标志,看看是否有任何奇怪的事情发生。它揭示了一个新的警告:

character.cpp(364): warning C4723: potential divide by 0

奇怪的是在那一点附近没有任何除法:

//Currently hp is always equal to 30
for (int i = 0; i < hp; i++) {
    int startXPos = i*12 + 40;
    if (i == hp-1) {
        gfx.DrawLine(10+startXPos,15,10+startXPos,40,245,245,245); //This line
        //This function expects: int, int, int, int, int, int, int
    }
}

现在此警告仅在我使用 /Ox - 标志(完全优化)编译时出现。使用 /Od(无优化)编译时,我没有收到警告。

我的问题是:我是否应该忽略这个警告(也许禁止它)?还是我应该担心?是什么原因造成的?

更新:

DrawLine函数的一部分:

int dx = x2 - x1;
int dy = y2 - y1;

if( dy == 0 && dx == 0 ) {
    //1 pixel line
}
else if( std::abs( dy ) > std::abs( dx ) ) {
    if( dy < 0 ) {
        std::swap(x1,x2);
        std::swap(y1,y2);
    }
    float m = static_cast<float>(dx / dy);
    //No different/more division past this point

最佳答案

出现警告是因为“dy”有可能为零:

int dy = y2 - y1;

'dy' 用于分隔:

float m = static_cast<float>(dx / dy);

如果 'y2' 和 'y1' 具有相同的值,则与这样做相同:

float m = static_cast<float>(dx / 0);

很难知道如何正确修复,因为我们没有完整的算法,但至少:在将 dy 用作除数之前先检查它。例如(快速 n 肮脏的例子):

float m = static_cast<float>(dy ? dx/dy : 0);     // 0 depends on your algorithm...

或者您可以将所有线条剪裁在一起,将 y1 和 y2 解释为一条根本不应该绘制的无限小线条,在这种情况下,如果 dx 或 dy 等于 0,您将立即退出 DrawLine 函数。

关于c++ - 除以 0 警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20577649/

相关文章:

c# - 热拖如何在 Visual Studio 2012 (C Sharp) 中使用变量或方法?

c++ - && 什么时候表示 'forwarding reference' ?

C++ 对象转字符串

c++ - 为什么这个断言失败了?

c++ - 当我尝试写入二维数组时出现未处理的异常

c++ - VS 2012 错误 LNK2001 : unresolved external symbol

mysql - Lightswitch v3.0 : "Invalid URI: The Uri string is too long." 中的图像

c++ - 使用 boost::deadline_timer 延迟操作

c++ - 结构定义后的变量名

visual-studio-2012 - 转换此节点的正确xdt:Locator参数是什么?