我有一个家庭作业问题,要求用户提供位于三维空间中的矩形棱镜的顶点。我需要计算棱镜的表面积和体积。我必须有一个计算棱镜上两点之间距离的函数,我能够询问用户获取坐标的信息
double cx1, cy1, cz1, cx2, cy2, cz2, cx3, cy3, cz3, cx4, cy4, cz4, cx5, cy5, cz5, cx6, cy6, cz6, cx7, cy7, cz7, cx8, cy8, cz8;
int main() {
printf("Enter the first coordinate in the form x y z: \n");
scanf("%lf %lf %lf", &cx1, &cy1, &cz1);
printf("Enter the second coordinate in the form x y z: \n");
scanf("%lf %lf %lf", &cx2, &cy2, &cz2);
printf("Enter the third coordinate in the form x y z: \n");
scanf("%lf %lf %lf", &cx3, &cy3, &cz3);
printf("Enter the fourth coordinate in the form x y z: \n");
scanf("%lf %lf %lf", &cx4, &cy4, &cz4 );
printf("Enter the fifth coordinate in the form x y z: \n");
scanf("%lf %lf %lf", &cx5, & cy5, &cz5);
printf("Enter the sixth coordinate in the form x y z: \n");
scanf("%lf %lf %lf", &cx6, &cy6, &cz6);
printf("Enter the seventh coordinate in the form x y z: \n");
scanf("%lf %lf %lf", &cx7, &cy7, &cz7);
printf("Enter the eighth coordinate in the form x y z: \n");
scanf("%lf %lf %lf",&cx8, &cy8, &cz8);
return get_dist(cx1, cx2, cy1, cy2);
}
然后我将每个x y和z坐标分配给一个变量,这在主函数中都是...然后我这样做了一个点:
double get_dist(cx1,cx2,cy1, cy2){
double distance1_2;
distance1_2 = sqrt(((cx2 - cx1)*(cx2 - cx1)) - ((cy2 - cy1)*(cy2 - cy1)) );
printf("%lf",distance1_2);
return 0;
}
并且它给了我正确的值2,但这样做是否比单独执行每个坐标更容易/更快?
答案 0 :(得分:2)
这是你可以通过这么多变量减少头痛的原因:
像这样:
struct Point3 {
double x, y, z;
}; // <-- the semocolon (;) is mandatory here
// hack so that you can use `Point3` instead of `struct Point3` when
// referring to the structure type. This is completely unnecessary in C++
typedef struct Point3 Point3;
int const g_num_points = 8; // this is actually an instance where
// a global variable is arguably not that bad
int main() {
Point3 points[g_num_points]; // avoid global variables like plague
int i;
int ret;
for (i = 0; i < g_num_points; ++i) {
printf("Enter the %d'th coordinate in the form x y z: \n", i);
ret = scanf("%lf %lf %lf", &(points[i].x), &(points[i].y), &(points[i].z));
if (ret != 3) {
// deal with invalid input. Since this is homework
// I will leave it as an exercise for you
}
}
}
由于这是作业,我将让你弄清楚如何使用get_distance
结构编写Point3
函数。
顺便说一句,3d坐标中两点之间的距离涉及......好吧......两点,每个点有3个坐标,你有6个坐标。您的函数只需4个坐标作为输入参数。使用这样的结构来表示它的3个坐标点应该能够更明显地解决这个问题。