首页 > 解决方案 > c ++数学问题,如果数学都在同一行,则双精度数不返回值

问题描述

首先感谢本网站上所有精彩的问题和答案!这个网站是一个很好的资源,可以解决我过去遇到的许多问题,这些问题已经得到了解答。但是,我目前遇到了一个问题,我似乎无法找到解决方案..

我正在使用 OpenCV 尝试制作我的第一个 C++ 程序,但遇到了一个奇怪的数学问题。我猜这很简单,我没有看到,我希望有人能解释我做错了什么。

问题出在下面一行: double L1_Slope = (L1P2.y-L1P1.y) / (L1P2.x-L1P1.x); 如果我在同一行上进行所有数学运算,它会返回 0,但是如果我将其分成 3 行,它会给我我需要的输出。

我见过类似的问题,但它们都处理整数。L1P1,L1P2,L2P1,L2P2 实际上都是 cv::Point's - 它们是整数......但由于我将 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 << "\n\nL1P1.x=" << L1P1.x << "\n";
std::cout << "L1P1.y=" << L1P1.y << "\n";
std::cout << "L1P2.x=" << L1P2.x << "\n";
std::cout << "L1P2.y=" << L1P2.y << "\n\n";

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 << "\n\n";

double L1_Slope = (L1P2.y-L1P1.y) / (L1P2.x-L1P1.x);
std::cout << "L1_Slope=" << L1_Slope << "\n\n";

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

标签: c++opencv

解决方案


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

这里,xy坐标是整数。该表达式的计算结果为:

(345 - 62) / (578 - 111)

或者

283 / 467

你会惊讶地发现,在 C++ 中,283 / 467是 0。这是整数除法,并且作为整数执行,没有小数部分。即使最终结果被分配给 a 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


推荐阅读