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

Why does a calculation not work when the calculation is placed in the code before the input of the parameters?

本文关键字:计算 代码 不起作用 输入 为什么 参数      更新时间:2023-10-16

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

您的期望是:

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