我有一个工作程序,要求用户选择写入文件或读取文件。如果用户选择写入,程序将要求两个点,然后以“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)
其中dx
是x2-x1
,dy
是y2-y1
。
关于c - 尝试添加代码来计算两个用户输入点之间的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23269809/