java - 修正java中的公式
问题描述
我的第一个任务要求我编写一个表达公式的程序。作业中写的公式:
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();
}
推荐阅读
- java - 遇到此问题 *使用 -Xlint 重新编译:未选中以获取详细信息。*
- reactjs - Material-UI 更改默认颜色
- ios - 如何在 UIDocumentPickerViewController 中更新框架大小的样式
- mfc - 如何在 MFC 中使用相同的序列化方法将信息保存在两个文件中
- postgresql - 分区和索引
- android - WebP 快速压缩
- javascript - 当对象没有引号时将对象转换为数组javascript
- javascript - js - 如何在 Promise .then() 中调用异步函数
- c# - 如何在 ASP.NET Core 中流式传输文件后删除文件
- android - 如何在 WebView 中打开 target=_blank 链接