C 数学问题,如果数学全部在同一行上,则双重返回值

c++ Math Issue, Double not returning value if math is all on the same line

本文关键字:一行 重返 返回值 如果 问题 全部      更新时间:2023-10-16

首先,请感谢本网站上所有的好问题和答案!该网站是解决我许多人过去曾经回答过的许多问题的重要资源。但是,我目前有一个问题,我似乎找不到解决方案。

我正在与OpenCV合作,试图制作我的第一个C 程序,并且正在遇到一个奇怪的数学问题。我猜想这很简单,我没有看到,希望有人可以解释我做错了什么。

问题在下面的行上: double l1_slope =(l1p2.y-l1p1.y)/(l1p2.x-l1p1.x); >如果我在同一行上全部进行数学,则它将返回0,但是如果我将其分解为3行,它会给我所需的输出。

我已经看到了类似的问题,但是它们都与整数打交道。L1P1,L1P2,L2P1,L2P2实际上是所有CV :: Point的 - 都是整数...但是,由于我将L1_Slope宣布为双重,因此我不知道为什么会如此。

有什么想法吗?我知道我可以打破数学,它将起作用,但是我无法想象无法在一行上进行此数学。

cv::Point calcIntersection(cv::Point L1P1, cv::Point L1P2, cv::Point L2P1, cv::Point L2P2) {
//calculates the intersection of two lines
std::cout << "nnL1P1.x=" << L1P1.x << "n";
std::cout << "L1P1.y=" << L1P1.y << "n";
std::cout << "L1P2.x=" << L1P2.x << "n";
std::cout << "L1P2.y=" << L1P2.y << "nn";
double test1 = (L1P2.y - L1P1.y);
double test2 = (L1P2.x - L1P1.x);
double test3 = test1/test2;
std::cout << "test1=" << test1 << "n";
std::cout << "test2=" << test2 << "n";
std::cout << "test3=" << test3 << "nn";
double L1_Slope = (L1P2.y-L1P1.y) / (L1P2.x-L1P1.x);
std::cout << "L1_Slope=" << L1_Slope << "nn";
double L1_Intersect = L1P1.y - L1_Slope * L1P1.x;
double L2_Slope = (L2P2.y - L2P1.y) / (L2P2.x - L2P1.x);
std::cout << "L2_Slope=" << L2_Slope << "n";
double L2_Intersect = L2P2.y - L2_Slope * L2P2.x;
double intersectionX = (L2_Intersect - L1_Intersect) / (L1_Slope - L2_Slope);
double intersectionY = (L1_Slope * intersectionX + L1_Intersect);
cv::Point intersection = { static_cast<int>(intersectionX), static_cast<int>(intersectionY) };
return intersection;}

这是控制台中正在输出的内容:

L1P1.x=111
L1P1.y=62
L1P2.x=578
L1P2.y=345
test1=283
test2=467
test3=0.605996
L1_Slope=0
L2_Slope=0
double L1_Slope = (L1P2.y-L1P1.y) / (L1P2.x-L1P1.x);

在这里,xy坐标是整数。表达式评估为:

(345 - 62) / (578 - 111)

283 / 467

您会惊讶地发现,在C 中,283 / 467是0。这是整数部门,并且作为整数进行,没有分数部分。即使最终结果分配给double,也为时已晚。该部门首先进行评估。分数部分已经被截断,因此最终结果为0。

double test1 = (L1P2.y - L1P1.y);
double test2 = (L1P2.x - L1P1.x);
double test3 = test1/test2;

在这里,您将分子和分母存储到double变量中,然后分别将两个double值分开:

283.0 / 467.0

这现在是浮点部门,结果为.605996

表达式是根据其类型评估的,而不是分配结果的变量的类型。

分别进行数学并将每个结果分配给double变量时,您将隐式地将子表达施加到double。因此,实际上您有类似

的东西
double L1_Slope = static_cast<double>(L1P2.y-L1P1.y) / static_cast<double>(L1P2.x-L1P1.x);

当您将其全部放入一个没有(隐式或显式)铸件的表达式中时,您正在做整数数学,更像

int L1_Slope_int = (L1P2.y-L1P1.y) / (L1P2.x-L1P1.x);
double L1_Slope = L1_Slope_int;

在这种情况下,如果x差超过y差,则舍入将意味着您的分数较小,将变成整数0。

要将数学迫使double,您需要确保每个操作的至少一个操作数为double(如有必要,另一个操作将隐含地升起)。您可以通过将一个或多个子表达的结果分配给double变量,如您所见,或通过明确施放给double,如本答案中的第一个片段所示。