为什么在输入参数之前将计算放在代码中时计算不起作用?

时间:2018-02-08 21:48:32

标签: c++

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;
}

1 个答案:

答案 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));