【发布时间】:2014-12-18 10:42:44
【问题描述】:
我正在用 C++ 编写距离公式的程序。 x1=0 y1=0 x2=1 y2=1 的答案应该是 1.14 左右,但打印出来的答案是 2.00。每个变量都存储为 double 我不知道这里出了什么问题。这是我的代码,感谢您的帮助!!
// main.cpp
// Chap6_42
//
// Created on 10/21/14.
//
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
double distance(double,double,double,double); //distance prototype
int main()
{
double d = 0;
double x1 = 0; //coordinate x1
double x2 = 0; //coord x2
double y1 = 0; //coord y1
double y2 = 0; //coord y2
cout << "Enter four cords (x1,y1,x2,y2) to find the distance between them " << endl;
cout << "x1 = ";
cin >> x1;
cout << "y1 = ";
cin >> y1;
cout << "x2 = ";
cin >> x2;
cout << "y2 = ";
cin >> y2;
d = distance (x2,x1, y2,y1); //calls to distance function, performs computations
cout << "The distance is " << fixed << setprecision(2) << showpoint << d << endl;
return 0;
}
double distance(double x2,double x1,double y2,double y1) //distance function header
{
return sqrt(pow(x2-x1,2.0)) + sqrt(pow(y2-y1,2.0)); //distance function computations
}
//function definition
【问题讨论】:
-
毕达哥拉斯(因此投反对票)- 抱歉
-
除了反对票之外,为什么每个人都用“pow(x,2.0)”发布答案。基本上有 3 个错误的答案,因为“pow(-3.0,2.0)”返回“-9.0”,在这种情况下是错误的,因为 Zach 想要毕达哥拉。
-
@DarioOO 这个问题不是那个帖子的重复。这个问题是关于用
using namespace std;污染全局命名空间并导致函数名称解析问题。