# cos(x) program

Printable View

• November 6th, 2013, 10:53 AM
anon314
cos(x) program
I cannot figure out what I did wrong with this code to calculate cos(x), the function for the program is attached!

package cosx;

import java.util.Scanner;

public class cosx {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);

System.out.print("Enter amount in degrees: ");
double degrees = input.nextDouble();
System.out.print("Enter the number of series: ");
int n = input.nextInt();

System.out.println(getCos(degrees, n));
System.out.println(Math.cos(convertToRadians(degre es)));
}

public static double getCos(double degrees, int n) {
double cos = 0;
double numerator = 0;
int denominator = 0;
for (int i = 0; i <= n; i++, i++) {
numerator = getNumerator(Math.pow(-1, i));
denominator = getFactorial(2 * i);
cos += numerator / denominator;
}
return cos;
}

public static double convertToRadians(double degrees) {
return degrees * Math.PI / 180;
}

public static int getFactorial(int n) {
int factorial = 1;
for (int i = 1; i <= n; i++) {
factorial *= i;
}
return factorial;
}

public static double getNumerator(double degrees, int n) {
return convertToRadians(degrees) * Math.pow(-1, n);
}

}
• November 6th, 2013, 12:53 PM
Norm
Re: cos(x) program
Quote:

what I did wrong with this code
Please explain.

Attachment image too small.

Please edit your post and wrap your code with code tags:
[code=java]
YOUR CODE HERE
[/code]
to get highlighting and preserve formatting.