c ++ 2点分配之间的距离

时间:2018-01-29 23:09:57

标签: c++

人们,我对我的一个编程任务有疑问。赋值是写一个名为nearest.cpp的完整C ++程序,它以下列格式从标准输入读取三个点p1 =(x1,y1),p2 =(x2,y2)和p3 =(x3,y3)。我创建的函数对于我的老师希望我们在主程序中使用它们的项目是强制性的,我确切地设置了它。我的程序编译但是每次我运行我的程序输出时似乎都没有得到用户的输入

x1 y1
x2 y2
x3 y3

1.0 3.0
1.5 7.2
4.0 2.0
The three points are:
  0.000      0.000 
  0.000      0.000 
  0.000      0.000 
The closest two points are:
 0.000      0.000
 0.000      0.000 

The distance between those two points is:      0.000
The closest two points are:
 0.000      0.000
 0.000      0.000 

The distance between those two points is:      0.000
The closest two points are:
 0.000      0.000
 0.000      0.000 

The distance between those two points is:      0.000

何时打印出来

The three points are:
 1.000      3.000
 1.500      7.200
 4.000      2.000

The closest two points are:
 1.000      3.000
 4.000      2.000

The distance between those two points is:      3.162

这是正确的输出

#include <cstdio>
#include <cmath>
using namespace std;

void displayInput(double x1, double y1, double x2, double y2, double x3, 
double y3)
{
printf("The three points are:\n %10.3f %10.3f \n %10.3f %10.3f \n %10.3f 
%10.3f \n",
x1, y1, x2, y2, x3, y3);
}


double distance(double x1, double y1, double x2, double y2)
{
double value = pow (x1 - x2, 2) + pow(y1 - y2, 2);
return sqrt(value);
}

void showOutput(double x1, double y1, double x2, double y2, double d)
{
printf("The closest two points are:\n%10.3f %10.3f\n%10.3f %10.3f \n"
"\nThe distance between those two points is: %10.3f\n",
x1, y1, x2, y2,d);
}

void consider(double x1, double y1, double x2, double y2, double x3, double 
y3)
{
double ans1, ans2, ans3;
ans1 = distance(x1, y1, x2, y2);
ans2 = distance(x1, y1, x3, y3);
ans3 = distance(x2, y2, x3, y3);

 if (ans1 <= ans2 && ans1 <= ans3)
  {
   showOutput(x1, y1, x2, y2, ans1);
  }
}


int main()
{
double x1, x2, y1, y2, x3, y3;

scanf("%f%f%f%f%f%f", &x1, &y1, &x2, &y2, &x3, &y3);

displayInput(x1, y1, x2, y2, x3, y3);

consider(x1, y1, x2, y2, x3, y3);
consider(x1, y1, x3, y3, x2, x2);
consider(x2, y2, x3, y3, x1, y1);
return 0;
}

2 个答案:

答案 0 :(得分:1)

scanf的格式更改为"%lf%lf%lf%lf%lf%lf"后,您也可以更正此行:

consider(x1, y1, x3, y3, x2, x2);
                            ^^^^ //<-- should be y2, no?

Copypasta是无情的!

答案 1 :(得分:0)

您的比较功能并未考虑所有组合 这是一个例子:

double shortest_distance = ans1;
double shortest_x1 = x1;
double shortest_y1 = y1;
double shortest_x2 = x2;
double shortest_y2 = y2;

if (ans2 < shortest_distance)
{
  shortest_distance = ans2;
  shortest_x1 = x1;
  shortest_y1 = y1;
  shortest_x2 = x3;
  shortest_y2 = y3;
}
if (ans3 < shortest_distance)
{
  shortest_distance = ans3;
  shortest_x1 = x2;
  shortest_y1 = y2;
  shortest_x2 = x3;
  shortest_y2 = y3;
}
showOutput(shortest_x1, shortest_y1,
           shortest_x2, shortest_y2,
           shortest_distance);