2017-06-02 50 views
-2
  1. 这是问题,我试图从弧度转换成度,并弹出一个度数为theta2的数字。然而,对于弧度theta2(rtheta2)和theta2本身,保持返回0。公式是正确的,我想,所以也许是一个格式错误?为什么我得到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); 
    
+0

计算结果发生是偶然你的意思'rtheta2 = ASIN((N1/N2 )* sin(rtheta1));'而不是theta2? – Ctx

+0

并删除所有这些空行...... –

+0

无论哪种方式,如果我将它们互换,我仍然得到0 rtheta2和theta2。你是什​​么意思空行?我想它更容易阅读。情况并非如此吗? –

回答

3

使用浮点运算,而不是整数除法。

整数除法结果为整数商,但代码需要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); 

要当心asin()范围[-1.0...+1.0]之外这可能与附近的+/- 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); 
+0

非常有帮助,谢谢! –