问题是输入 10 个点 (x,y)。程序应该找到连续点之间的距离,并将输出作为“距离总和”或第一个和最后一个点之间的距离。我正在使用 Ubuntu 18.04 LTS 终端。
程序运行
输入
(Enter the coordinates of the 10 points.)
1.000000 2.000000
3.000000 4.000000
5.000000 6.000000
7.000000 8.000000
9.000000 10.000000
11.000000 12.000000
1.000000 13.000000
14.000000 15.000000
16.000000 17.000000
18.000000 19.000000
输出
Entered points:
1.000000 2.000000
3.000000 4.000000
5.000000 6.000000
7.000000 8.000000
9.000000 10.000000
11.000000 12.000000
1.000000 13.000000
14.000000 15.000000
16.000000 17.000000
18.000000 19.000000
Distance between first and last point is: inf.
代码
#include <stdio.h>
#include <math.h>
int main()
{
int i,j;
double points[10][2],dist = 0;
printf("Enter the coordinates of the 10 points.\n");
for(i=0;i<10;i++)
{
for(j=0;j<2;j++)
{
scanf("%lf",&points[i][j]);
}
}
printf("Entered points:\n");
for(i=0;i<10;i++)
{
for(j=0;j<2;j++)
{
printf("%f ",points[i][j]);
}
printf("\n");
}
printf("\n");
for(i=0;i<10;i++)
{
dist = dist + sqrt(pow((points[i][0]-points[i+1][0]),2)+pow((points[i][1]-points[i+1][1]),2));
}
printf("Distance between first and last point is: %f.\n",dist);
return 0;
}
您的 [第三个]for
循环正在遍历数组的末尾,并且您正在获取垃圾/未定义的数据。
在您的计算循环中,您正在使用 (eg) points[i+1][0]
。在最后一次迭代中,i
将是9
,因此i+1
将是 10。这是最后一次。
将循环数减少到 9。您正在比较点对,因此您需要减少计数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句