提示用户输入两个点的坐标,然后计算并输出这两个点之间的距离。两点坐标为(x1,y1), (x2,y2),距离为对应坐标差的平方和,再开平方。输出的距离保留4位小数。
求解答 为什么计算结果不正确
#include
#include
#include
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv) {
cout<<"Please input the coordinates of two points:"<"point 1(x,y):"<"point 2(x,y):"<double x1,x2,y1,y2,distance;
cin>>(x1,y1)>>(x2,y2);
distance=sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
cout<<"This distance is:"<setprecision(4)<return 0;
}
#include <cmath>
#include <iomanip>
#include <iostream>
using namespace std;
int main(int argc, char **argv) {
double x1, x2, y1, y2, distance;
char ch;
cout << "Please input the coordinates of two points:" << endl;
cout << "point 1(x,y): ";
cin >> ch >> x1 >> ch >> y1 >> ch;
cout << "point 2(x,y): ";
cin >> ch >> x2 >> ch >> y2 >> ch;
distance = sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
cout << "This distance is:" << fixed << setprecision(4) << distance << endl;
return 0;
}
$ g++ -Wall main.cpp
$ ./a.out
Please input the coordinates of two points:
point 1(x,y): (1,1)
point 2(x,y): (2,2)
This distance is: 1.4142
#include <iostream>
#include<math.h>
#include<iomanip>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv) {
cout<<"Please input the coordinates of two points:"<<endl;
double x1,x2,y1,y2,distance;
cout<<"point 1(x,y):"<<endl;
cout<<"point 1 X:"<<endl;
cin>> x1 ;
cout<<"point 1 Y:"<<endl;
cin>> y1;
cout<<"point 2(x,y):"<<endl;
cout<<"point 2 X:"<<endl;
cin>> x2 ;
cout<<"point 2 Y:"<<endl;
cin>> y2;
distance=sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
cout<<"This distance is:"<<fixed<<setprecision(4)<<distance<<endl;
return 0;
}