使用cos()函数计算余弦值结果不符合预期的技术求助
问题分析与解决
嘿,我一眼就看出问题所在了——你犯了一个很多C语言新手都会踩的坑:C标准库中的cos()(以及sin()、tan()等三角函数)要求的输入是弧度**,而不是你输入的角度!**
为什么会得到-7.62?
你输入的60是角度,但cos(60)会直接把它当成60弧度来计算。60弧度换算成角度大概是 60 × (180/π) ≈ 3437.75度,这个角度对应的余弦值本身就是负数,和你得到的-7.62结果完全吻合。
解决方法:角度转弧度
要得到正确的结果,你需要先把输入的角度转换成弧度,转换公式是:
弧度 = 角度 × π ÷ 180
C标准库提供了M_PI宏来表示π,但要注意必须在包含<math.h>之前定义_USE_MATH_DEFINES(部分编译器如MSVC需要这个定义才能启用M_PI,GCC通常不需要,但加上能提升代码兼容性)。
修改后的代码
#define _USE_MATH_DEFINES // 必须放在#include <math.h>之前 #include <stdio.h> #include <math.h> #include <stdlib.h> int main() { float magnitudeForce; int force; float theta; float angle; double x; double y; int i = 0; while(i < 3){ printf("Please enter the value of the force and the angle from the x-axis of the force:\n"); scanf("%d %f", &force, &angle); printf("The force and the angle are: %d %.2f.\n", force, angle); // angle是float类型,用%.2f更匹配 // 把角度转换为弧度 double radians = angle * M_PI / 180.0; x = force * cos(radians); printf("Calculated x-component: %.2lf\n", x); // 格式化输出更直观 ++i; } return 0; }
测试验证
当你输入8 60时:
- 60角度转换成弧度是
60 × π ÷ 180 = π/3 ≈ 1.047 cos(π/3) = 0.5- 最终计算结果
8 × 0.5 = 4,完全符合你的预期!
内容的提问来源于stack exchange,提问作者A. Cervantes
相关产品推荐
相关产品推荐

