x1 = 7,x2 = 3,y1 = 12,y2 = 9的值的正确答案应该是5.这段代码给了我5.9 ...我无法弄清楚是什么问题是。
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
int main()
{
int x1, x2, y1, y2;
double distance;
distance = sqrt(pow((x2-x1), 2) + pow((y2-y1), 2));
cout << "Enter x1: ";
cin >> x1;
cout << "Enter x2: ";
cin >> x2;
cout << "Enter y1: ";
cin >> y1;
cout << "Enter y2: ";
cin >> y2;
cout << "The distance between two points is: " << distance << endl;
return 0;
}
答案 0 :(得分:3)
您的期望:
distance = sqrt(pow((x2-x1), 2) + pow((y2-y1), 2));
将使用用户输入无根据的变量值。执行该行时,不会初始化变量x1
等。因此,您的程序有不确定的行为。
在您阅读y2
的行之后移动该行。
// Not good to be here.
// distance = sqrt(pow((x2-x1), 2) + pow((y2-y1), 2));
cout << "Enter x1: ";
cin >> x1;
cout << "Enter x2: ";
cin >> x2;
cout << "Enter y1: ";
cin >> y1;
cout << "Enter y2: ";
cin >> y2;
distance = sqrt(pow((x2-x1), 2) + pow((y2-y1), 2));