gpt4 book ai didi

c++ - 除以 0 警告

转载 作者:太空狗 更新时间:2023-10-29 23:17:05 28 4
gpt4 key购买 nike

我一直在处理一个应用程序,因为图像表现得很奇怪,所以我决定打开 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com