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

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

最佳答案

您的期望:

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

关于c++ - 为什么在输入参数之前将计算放在代码中时计算不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48695326/

相关文章:

c++ - 在 C++ 中由 ‘Sequentially Consistent Atomics’ 语义实现时,DCL(双重检查锁定)是否线程安全?

c++ - 运行时如何在 Visual Studio C++ 中确定调试或 Release模式

c++ - 使用线程编程时出现 std::thread::_Invoker 错误

c++ - 在 Windows 中获取下一个打开的 tcp 端口

c++ - 适用于头文件的函数别名

c++ - 加密和解密未显示正确的值

c++ - 错误: anachronistic old-style base class initializer

c++ - 如何检查我的 Linux Box 安装是否具有 SSE 指令功能?

c++ - 候选模板被忽略 : deduced type does not match adjusted type

c++ - memcpy,其中大小在编译时已知