为什么在参数输入之前将计算放置在代码中时,计算不起作用
Why does a calculation not work when the calculation is placed in the code before the input of the parameters?
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));
相关文章:
- 我的字符计数代码计算错误.为什么
- 计算每个节点的树高,帮助我解释这个代码解决方案
- 代码在我的计算机上运行良好,但是在将其提交给coursera时遇到未知的信号11问题
- 计算两个代码块的时间复杂度
- 计算出有多少客户端可以连接到我正在使用的一些tcp服务器代码
- 如果代码包含多个复杂度循环,如何计算复杂度
- 在实现合并排序代码时无法计算所有反转
- 如何在数组类型的模板代码中计算std::size_t
- 为什么这两个相似的代码计算行列式的结果不同?
- 根据计算机上安装的库依赖项编译不同的代码
- 此代码如何计算数字的奇偶校验?
- 代码的最优解,以便它可以执行高达 10^18 的计算
- 交叉和计算,任何人都可以解释代码吗?
- 使用额外的变量使计算更容易理解 - (多少)我减慢了代码的速度?
- 计算代码块的 O 表示法
- 计算代码行数
- 如何计算C++代码段的 CPU 周期成本
- 如何更快地计算代码
- 我如何改进这个GPA计算代码
- 在高度优化的代码中计算代码运行时