Problem Description
输入两点坐标(X1,Y1),(X2,Y2),计算并输出两点间的距离。
Input
输入数据有多组,每组占一行,由4个实数组成,分别表示x1,y1,x2,y2,数据之间用空格隔开。
Output
对于每组输入数据,输出一行,结果保留两位小数。
Sample Input
0 0 0 1
0 1 1 0
Sample Output
1.00
1.41
这是我写的代码:
//输入两点坐标(X1, Y1), (X2, Y2), 计算并输出两点间的距离。
#include <iostream>
#include <cmath>
#include <vector>
#include <iomanip>
using namespace std;
int main(void)
{
float px, py, qx, qy;
while (cin >> px >> py >> qx >> qy)
{
int tmp = pow((px - qx), 2) + pow((py - qy), 2);
double res = sqrt(tmp);
cout << setiosflags(ios::fixed);
cout << setprecision(2) << res << endl;
}
return 0;
}
程序应该是这样的:输入一行,按回车显示结果。如果这时再按回车,程序就结束。(误)
问题就是不知道怎么停止输入,只能按ctrl+z或者输入非法字符。
请问在C++里如何实现?不用C
这是通过的C语言代码
#include <stdio.h>
#include <math.h>
int main(){
double x1;
double y1;
double x2;
double y2;
double result;
while((scanf("%lf%lf%lf%lf",&x1,&y1,&x2,&y2))!=EOF){
result=(x1-x2)*(x1-x2)+(y1-y2)*(y1-y2);
result=sqrt(result);
printf("%.2lf\n",result);
}
return 0;
}
我发现按回车也没用,现在我也不清楚机器判断通过的条件是什么。
有人能分析下为什么我的不能通过而上面的这个能够通过呢?
This kind of algorithm question generally accepts infinite input and does not require termination, unless there is a clear requirement for what input program should be terminated
First of all, let’s talk about your code
Then. .
F6 can also exit.
cin is the standard input stream object.
Enter any non-numeric characters. If the stream reading fails, an error will be marked and false will be returned.
F6 can jump out of the loop because it represents eof (end of file) .
ctrl+z directly terminates the program process.