c - 为什么我的输出结果是 0?与格式或公式有关吗?

标签 c floating-point

  1. 问题是,我正在尝试将弧度转换为度数,并为 theta2 弹出一个以度为单位的数字。然而,对于弧度 theta2(rtheta2) 和 theta2 本身,继续返回 0。我认为该公式是正确的,所以可能是格式错误?

  2. 这是我的代码:

    #include <stdlib.h>
    #include <math.h>
    
    #define PI 3.14159
    
    int main(void)
    {
        char input;
        int n1;
        float rn1;
        int n2;
        float rn2;
        int theta1;
        float rtheta1;
        float rtheta2;
        float theta2;
    
        printf("      Program Snell's Law:\n");
        printf("--------------------------------");
        printf("\n\nA> Enter indices of refraction of first angle.");
        printf("\nB> Calculate second angle of incdience.\n");
    
        scanf("%c", &input);
        printf("A> Enter indices of refraction of first angle.\n");
        scanf("%d", &n1);
    
        printf("Enter the index of material 2:\n");
        scanf("%d", &n2);
    
        printf("Enter the angle of incidence in region 1:\n");
        scanf("%d", &theta1);
    
        rn1=(M_PI /180) * n1;
        rn2=(M_PI /180) * n2;
        rtheta1=(M_PI /180) * theta1;
    
        theta2=asin((n1/n2) * sin(rtheta1));
    
        //need to convert back into degrees for radians theta 2~
        theta2=rtheta2*(180/M_PI);
    
        printf("%lf", rn1);
        printf("\n%lf", rn2);
        printf("\n%lf", rtheta1);
    
        printf("\n%lf", theta2);
        printf("\n%lf", rtheta2);
    

最佳答案

使用 float 学而不是整数除法。

整数除法产生整数商,但代码需要 FP 结果。

int n1, n2;
...
//                 v--- integer division.
// theta2= asin((n1/n2) * sin(rtheta1));
theta2 = asin((1.0*n1/n2) * sin(rtheta1));

// or re-order to effect FP divsiosn
theta2 = asin(sin(rtheta1)*n1/n2);
<小时/>

注意在 [-1.0...+1.0] 范围之外使用 asin(),这可能会导致计算结果接近 +/- 1.0

double y = (1.0*n1/n2) * sin(rtheta1);
if (y > 1.0) y = 1.0;
else if (y < -1.0) y = -1.0;
theta2 = asin(y);

关于c - 为什么我的输出结果是 0?与格式或公式有关吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44333018/

相关文章:

c++ - gcc 中的位域字节顺序

c - libusb_set_interface_alt_setting () 有什么作用?

pthread_mutex_lock() 能否在 pthread_cond_wait() 解除阻塞之前解除阻塞?

c - Unix 套接字 : when to use bind() function?

binary - 如何将 float 转换为二进制?

Linux shell : Changing decimal (float) separator from dot to comma

c - C中反转字符串的函数

floating-point - 逆向工程专有 float 编码

c - 相似的代码输出不同的结果

python - 从字符串中读取一个 float