c - 尝试添加代码来计算两个用户输入点之间的距离

标签 c distance

我有一个工作程序,要求用户选择写入文件或读取文件。如果用户选择写入,程序将要求两个点,然后以“Point(%d,%d)”的格式打印到文件中。我想做的是能够计算每个点之间的距离,以便如果用户愿意,可以显示总距离。澄清一下,距离为 (Point1->Point2)+(Point2->Point3)+(Point3->Point4),而不是 Point1->Point4。我相信我将不得不使用这样的方程式:
distance += sqrt((int)(...正在计算一些短值...)

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct point
{
        short int x;
        short int y;
}point;
int main(char ** args, int argc)
{
        point append;
        char choice;

        int i = 1;
        int c;
        char dump;

        while(i != 0)
        {
                printf("Enter a to append and c to calculate p to print\n:");
                scanf("%c%c", &choice, &dump);

                switch(choice)
                {
                        case 'a':
                        {
                                FILE * output;
                                output = fopen("test.bin", "ab+");
                                printf("Enter the x:\n");
                                scanf("%hu", &append.x);
                                printf("Enter the y:\n");
                                scanf("%hu%c", &append.y, &dump);
                                fprintf(output, "Point (%hu,%hu)\n", append.x, append.y);
                                fclose(output);
                                break;
                        }
                        case 'p':
                        {
                                FILE * print;
                                print = fopen("test.bin", "rb");
                                if(print)
                                {
                                        while((c = getc(print)) != EOF)
                                        {
                                                putchar(c);
                                        }
                                }
                                fclose(print);
                                break;
                        }
                        case 'q':
                        {
                                i = 0;
                                break;
                        }
                }
        }
}

最佳答案

使用distance formula找出每个线段的长度。将这些线段长度相加即可得出总距离。

距离公式取 x 和 y 变化的平方和的平方根:

Distance = sqrt(dx*dx + dy*dy)

其中dxx2-x1dyy2-y1

关于c - 尝试添加代码来计算两个用户输入点之间的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23269809/

相关文章:

list - flutter - 设置显示List距离时的最大半径

c - 在make mupdf期间, fatal error : X11/Xlib. h文件在mac中找不到

c - 线程在函数返回后停止

python - 在 Pandas 中将字典转换为对称/距离矩阵的最有效方法

swift - AND (&&) 运算符在 SWIFT 中未按预期工作

mysql - 在特定时间间隔的随机结果(根据列数据)

c - 奇怪的指针初始化

c - 基本的 C 指针分配/释放

c - 更新 CSV 文件中的数据

android - 哪一个最适合计算两点之间的距离?