用于计算用户输入的角度的正弦和余弦的程序

时间:2018-04-02 20:15:05

标签: java switch-statement do-while sine cosine

我一直在尝试编写一个程序,用户输入一个角度,假设它是度,它从度数转换为弧度,然后计算其正弦或余弦。我试图以一种方便用户的方式做到这一点,但事实证明我有一些问题试图计算这两个(余弦和正弦)并输出正确的结果。我感谢您的帮助。假设术语的常数为30。

import java.util.Scanner;

public class Question8 {
    public static double radians(double angle)
    {
        double pi = 3.141592653589793238462643;
        return angle / 180.0 * pi; //conversion from degrees to radians
    }

    public static void main( String [] args)
    {
        Scanner sc = new Scanner(System.in);
        int sw = 0, n, j=1, m=-1;
        double sine, i=0, r=0, cosine, c=0, rad; //initialising variables of type double and int

        do{
            System.out.println("Please input either 1 or 2 to calculate Sine or Cosine respectively.");
            sw = sc.nextInt();
            switch(sw) { //implementing a switch to differentiate between sine and cosine

                case 1:{ //this calculates the sine
                    System.out.println("Please input Angle and n (number of terms) to calculate sine");
                    sine = sc.nextDouble();
                    n = sc.nextInt();
                    rad = radians(sine);
                    i = rad;
                    for(int k = 3; k < n; k = k+2) {
                        double o = Math.pow(rad,k);
                        j = j*(k-1)*k;
                        r = o/j;
                        i=i+m*r;
                        m=m*(-1);

                    }
                    System.out.println("Sine " + sine + " = " + i);


                }
                break;

                case 2:{ //this calculates cosine
                    System.out.println("Please input angle and n to calculate cosine");
                    cosine = sc.nextDouble();
                    n = sc.nextInt();
                    rad = radians(cosine);
                    c = 1.0;
                    for(int k = 2; k < n; k = k+2) {
                        double o = Math.pow(rad,k);
                        j = j*(k-1)*k;
                        r = o/j;
                        c=c+m*r;
                        m = m*(-1);
                    }
                    System.out.println("Cosine " + cosine + " = " + c);

                }
                break;

                default: {
                    System.out.println("Invalid choice"); //user selects invalid numbers
                }
                break;
            }
        } while(sw != 0);
    }
}

1 个答案:

答案 0 :(得分:1)

计算sin和cos的算法是正确的。您应该在每次演算后重新初始化变量mjr。您可以使用CORDIC algorithmchebyshev polynomial作为Taylor series的更准确替代。