c++ - 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
解决方案
double L1_Slope = (L1P2.y-L1P1.y) / (L1P2.x-L1P1.x);
这里,x
和y
坐标是整数。该表达式的计算结果为:
(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
推荐阅读
- perl - 在perl中通过套接字传递文件名
- c++ - 试图访问成员函数中的另一个类 - CPP
- php - 在`php -a`之前引导PHP文件
- c++ - C++:从父类访问子成员
- google-cloud-datalab - 我无法在 datalab 中使用 Google Cloud Translation API
- java - 如何在 Java 中的 Scanner 的现有分隔符中添加逗号?
- sql - SQL - 给定数据序列,我如何查询来源?
- similarity - 作为概率的文本相似性(0 到 1 之间)
- javascript - Java 脚本抛出解析错误“标识符”
- python - 让 PyLint 和 VSCode 自动补全理解相对导入