问题描述
我的第一次作业要求我编写一个表达公式的程序。作业中编写的公式:
y = 4x^3 + 8x^2 - 31x - 35 / (3x2 + 1)^1/2 + 2 * | x - 1.5 |
|表示绝对值; (...)1/2表示平方根
我还应该如何创建一个打印公式多少次以正数或负数或零打印的代码?
这是我创建作业程序的方式:
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();
}
}
解决方法
好的,您想对一个简单的数学公式进行测试。您必须测试结果并定义多少个结果为正,负或等于0 ... 您必须更新测试...结果等于0,您的测试返回肯定,否定和空结果。
您还必须计算结果。因此,为每种类型的结果实现计数器,并在if语句中增加它们。
public static void main(String[] args) throws IOException {
double x; double y;
int positive = 0;
int negative = 0;
int equalZero = 0;
PrintWriter outFile = new PrintWriter("testfile.txt");
for(x=-3.00; x <= 3.0; x = x + 0.50) {
y = Math.pow(4,3) + ... ( your formula)
System.out.println("X = " + x + "Y = " + y );
if (y < 0.0) {
System.out.println("Y is negative");
negative++;
} else if (y > 0.0) {
System.out.println("Y is positive");
positive++;
} else {
System.out.println("Y is zero");
equalZero++;
}
}
System.out.println();
System.out.println("Positive results : " + positive);
System.out.println("Negative results : " + negative);
System.out.println("Equal to zero : " + equalZero);
outFile.close();
}
,
使用不同的变量计算分母和分子,这将提高可读性,并且您可以轻松发现错误。
此外,您为y指定的条件:(y <= 0.0) and (y >= 0.0)
对于零将成立,因此无法达到最后一个条件y == 0.0
。