我正在尝试编写一个程序来查找 3D 矢量的大小。我需要使用一个函数来查找幅度(该程序还查找两个向量的点积,但我现在正在研究幅度部分)。该程序首先询问用户是否要求点积或幅度,当用户选择幅度时,它会要求提供 3 个向量值。然而,它返回了错误的东西。如果我输入1,2,3向量的分量,它将返回292044616。我认为问题出在我的函数调用中,但我现在确定它是什么。这是我的代码:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
int main(void) {
double find_magnitude(double v1, double v2, double v3);
//double theta;
int v1, v2, v3;// w1, w2, w3, mag, dot;
char a;
//dot = (v1 * w1) + (v2 * w2) + (v3 * w3);
printf("Enter M/m or magnitude or D/d for the dot product and angle in degrees: ");
scanf("%c", &a);
if (a == 'M' || a == 'm') {
printf("Enter in values for v1, v2, and v3: ");
scanf("%d,%d,%d", &v1, &v2, &v3);
printf("%d", find_magnitude(v1, v2, v3));
}
return(0);
}
double find_magnitude(double v1, double v2, double v3) {
double mag;
mag = sqrt(pow(v1, 2) + pow(v2, 2) + pow(v3, 2));
return(mag);
}
Run Code Online (Sandbox Code Playgroud)
问题很简单:函数find_magnitude返回 adouble但你告诉printf将 an 转换int为%d。您应该使用%f格式说明符:
printf("%f\n", find_magnitude(v1, v2, v3));
Run Code Online (Sandbox Code Playgroud)
另请注意以下注释:
为了保持一致性,应将前向声明find_magnitude()放在全局范围内。正如声明的那样,定义和声明是独立的,不一致不会在编译时产生诊断,但会在运行时产生未定义的行为。由于这个原因和其他原因,在 C 中总是在全局范围内编写全局对象的声明被认为是更安全和惯用的。
变量v1,v2并且v3可能应该定义为double。
v1 * v1v1是计算 的平方的更简单、更有效的方法pow(v1, 2)。
scanf()应测试的返回值以检测无效或丢失的输入。
这是修改后的版本:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
double find_magnitude(double v1, double v2, double v3);
int main(void) {
double v1, v2, v3;
char a;
printf("Enter M/m or magnitude or D/d for the dot product and angle in degrees: ");
if (scanf("%c", &a) != 1)
return 1;
if (a == 'M' || a == 'm') {
printf("Enter in values for v1, v2, and v3: ");
if (scanf("%lf,%lf,%lf", &v1, &v2, &v3) == 3) {
printf("magnitude: %f\n", find_magnitude(v1, v2, v3));
} else {
printf("invalid input\n");
}
}
return 0;
}
double find_magnitude(double v1, double v2, double v3) {
double mag;
mag = sqrt(v1 * v1 + v2 * v2 + v3 * v3);
return mag;
}
Run Code Online (Sandbox Code Playgroud)
正如Eph所评论的,hypot()使用 中声明的函数可以更准确地计算 3D 向量的大小(或模数)<math.h>:
v1、v2和/或的值v3非常大、非常小或大小相差很大,计算sqrt(v1 * v1 + v2 * v2 + v3 * v3)可能会产生不准确的结果。hypot(v1, v2)应该用来代替sqrt(v1 * v1 + v2 * v2)2D 向量和hypot(v1, hypot(v2, v3))对于 3D 向量。这是一个修改版本find_magnitude:
double find_magnitude(double v1, double v2, double v3) {
return hypot(v1, hypot(v2, v3));
}
Run Code Online (Sandbox Code Playgroud)