C 为什么我得到无穷大作为输出?你能找出程序中的错误吗?
问题是输入10个点x,y。程序应找到连续点之间的距离,并将输出作为“距离之和”或第一个点与最后一个点之间的距离。我正在使用Ubuntu18.04 LTS终端 程序运行 输入 输出C 为什么我得到无穷大作为输出?你能找出程序中的错误吗?,c,arrays,C,Arrays,问题是输入10个点x,y。程序应找到连续点之间的距离,并将输出作为“距离之和”或第一个点与最后一个点之间的距离。我正在使用Ubuntu18.04 LTS终端 程序运行 输入 输出 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.0000
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.
代码
当i变为9时,点[i+1]未定义 请尝试以下修复:
for(i=0;i<9;i++)
{
printf("ivalue:%d\n", i);
dist = dist + sqrt(pow((points[i][0]-points[i+1] [0]),2)+pow((points[i][1]-points[i+1][1]),2));
}
它将输出:
第一个点和最后一个点之间的距离是:43.001812。您的[third]for循环正在迭代通过数组的末尾,您正在获取垃圾/未定义的数据
在计算循环中,您正在使用例如点[i+1][0]。在最后一次迭代中,我将是9,因此i+1将是10。这已经过去了
将循环数减少到9。您正在比较成对的点,因此需要减少计数。您是否尝试使用调试器?code.tio.c:28:57:警告:迭代9调用未定义的行为-如gcc-Wall-Wextra-pedantic-O2所说。@OznOg您是否给出了相同的输入?
#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(i=0;i<9;i++)
{
printf("ivalue:%d\n", i);
dist = dist + sqrt(pow((points[i][0]-points[i+1] [0]),2)+pow((points[i][1]-points[i+1][1]),2));
}