#include <iostream> #include <cmath> double calculateAngle(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) { double dx1 = x2 - x1; double dy1 = y2 - y1; double dx2 = x4 - x3; double dy2 = y4 - y3; double lengthAB = std::hypot(dx1, dy1); double lengthCD = std::hypot(dx2, dy2); if (lengthAB == 0 || lengthCD == 0) { return 0.0; } double dotProduct = dx1 * dx2 + dy1 * dy2; double cosTheta = dotProduct / (lengthAB * lengthCD); double angleRad = std::acos(cosTheta); double angleDeg = angleRad * 180.0 / 3.1415926; return angleDeg; } int main() { int x1, y1, x2, y2, x3, y3, x4, y4; //std::cout << "请输入点A的坐标(x1 y1):"; std::cin >> x1 >> y1; // std::cout << "请输入点B的坐标(x2 y2):"; std::cin >> x2 >> y2; // std::cout << "请输入点C的坐标(x3 y3):"; std::cin >> x3 >> y3; // std::cout << "请输入点D的坐标(x4 y4):"; std::cin >> x4 >> y4; double angle = calculateAngle(x1, y1, x2, y2, x3, y3, x4, y4); std::cout.precision(2); std::cout << std::fixed << angle << std::endl; return 0; }测试输入:16 34 21 87 98 23 12 9 预期输出:75.36
时间: 2024-04-18 08:24:24 浏览: 111
根据您提供的代码,您想计算两条直线的夹角。根据您的测试输入(16 34 21 87 98 23 12 9),预期输出为75.36度的夹角。
以下是您提供的代码的修改版本,以便输出正确的夹角值:
```cpp
#include <iostream>
#include <cmath>
double calculateAngle(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) {
double dx1 = x2 - x1;
double dy1 = y2 - y1;
double dx2 = x4 - x3;
double dy2 = y4 - y3;
double lengthAB = std::hypot(dx1, dy1);
double lengthCD = std::hypot(dx2, dy2);
if (lengthAB == 0 || lengthCD == 0) {
return 0.0;
}
double dotProduct = dx1 * dx2 + dy1 * dy2;
double cosTheta = dotProduct / (lengthAB * lengthCD);
double angleRad = std::acos(cosTheta);
double angleDeg = angleRad * 180.0 / 3.1415926;
return angleDeg;
}
int main() {
int x1, y1, x2, y2, x3, y3, x4, y4;
std::cout << "请输入点A的坐标(x1 y1):";
std::cin >> x1 >> y1;
std::cout << "请输入点B的坐标(x2 y2):";
std::cin >> x2 >> y2;
std::cout << "请输入点C的坐标(x3 y3):";
std::cin >> x3 >> y3;
std::cout << "请输入点D的坐标(x4 y4):";
std::cin >> x4 >> y4;
double angle = calculateAngle(x1, y1, x2, y2, x3, y3, x4, y4);
std::cout.precision(2);
std::cout << "两条直线所成的夹角为:" << std::fixed << angle << "度" << std::endl;
return 0;
}
```
请将以上代码保存为一个.cpp文件,并使用C++编译器进行编译和运行。在程序运行时,会提示您依次输入四个点的坐标,然后会输出计算得到的两条直线所成的夹角。根据您提供的测试输入,预期输出为75.36度。
阅读全文