My first assignment requires me to write a program that expresses a formula. The formula as written in the assignment :
y = 4x^3 + 8x^2 - 31x - 35 / (3x2 + 1)^1/2 + 2 * | x - 1.5 |
| means absolute value; (...)1/2 means square root
Also how should I create a code that prints how many times the formula prints out a positive or negative number or zero?
Here is how I created my assignment's program:
import java.io.*;
public class hw1 {
public static void main(String[] args) throws IOException
{
System.out.println("My name is Jibran Khan and this is the output of my first program.");
double x; double y;
PrintWriter outFile = new PrintWriter("testfile.txt");
for(x=-3.00; x <= 3.0; x = x + 0.50)
{
y=((4*(x*x*x))) + (8*(x*x))-(31*x)-35/Math.sqrt(3*x*x+1)+2* Math.abs(x-1.5);
System.out.println("X = " + x + "Y = " + y );
if (y<=0.0) System.out.println("Y is negative");
if (y>=0.0) System.out.println("Y is positive");
if (y == 0.0) System.out.println("Y is zero");
}
System.out.println();
System.out.println("My first program is complete");
outFile.close();
}
}
Calculate the Denominator and Numerator in different variables, that will give more readability and you will be able to spot the mistakes easily.
Also, the conditions you gave for y:
(y <= 0.0) and (y >= 0.0)
will be true for zero so the last conditiony == 0.0
is not reachable.