首页 > 解决方案 > 为什么我得到无穷大作为输出?你能找到程序中的错误吗?

问题描述

问题是输入 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;
 }

标签: carrays

解决方案


您的 [第三个]for循环正在遍历数组的末尾,并且您正在获取垃圾/未定义的数据。

在您的计算循环中,您正在使用 (eg) points[i+1][0]。在最后一次迭代中,i将是9,所以i+1将是 10。这是一个结束。

将循环数减少到 9。您正在比较点,因此您需要减少计数。


推荐阅读