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

时间:2014-04-24 13:05:47

标签: c distance

我有一个工作程序,要求用户选择写入文件或读取文件。如果用户选择写入,程序将要求两个点,然后以#34;点(%d,%d)和#34;的格式打印到文件中。我想要做的是能够计算每个点之间的距离,以便如果用户愿意,可以显示总距离。为了阐明,距离将是(Point1-> Point2)+(Point2-> Point3)+(Point3-> Point4),而不是Point1-> Point4。我相信我必须使用这样的等式:
距离+ = 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;
                        }
                }
        }
}

1 个答案:

答案 0 :(得分:1)

使用distance formula查找每个细分的长度。添加这些段长度以查找总距离。

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

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

dxx2-x1dyy2-y1

相关问题