c - 为什么我得到无穷大作为输出?你能找到程序中的错误吗?
问题描述
问题是输入 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。您正在比较点对,因此您需要减少计数。
推荐阅读
- postgresql - 为什么我对索引字段的计数查询很慢?
- reactjs - formik,将 Field 的道具传给孩子?
- jmeter - 我的 jmeter 负载测试和 Apdex 中出现错误 500/OK。500/OK是什么意思?
- android - 在 Android React Native 应用程序中正确使用 Intl
- amazon-web-services - 如何使我的 Airflow EC2 实例 HTTPS?
- python - 无法腌制 lxml.etree._Element 对象
- swiftui - 将 WKInterfaceTimer 添加到 SwiftUI
- awk - 使用 AWK 将变量写入冒号后的第 5 行
- unity3d - 围绕一个点统一旋转对象
- python - 使用 CFFI 构建 Python-C 扩展,但 Setuptools 在构建中不包含自定义头文件