gpt4 book ai didi

java - Double.toString(2.0) 在Java中不是 "2.0"?

转载 作者:行者123 更新时间:2023-11-30 03:46:52 25 4
gpt4 key购买 nike

我正在开发一个 Java 项目。这是一个简单的二次公式代码。但是当我想将 double 值转换为字符串时(其中 a=1.0、b=0 和 c= -4.0 in ax^2+bx+c)。我的测试失败了。我试图找出问题所在。我找到了它在哪里,显然 Double.toString(x) 其中 double x=2.0 没有返回 “2.0”。然后我尝试了String.valueOf(x),但也不起作用。然后我简单地输入“2.0”`,它通过了我的测试用例。

我哪里出错了?或者 Java 就是讨厌我。

编辑:哇你们这么快就评论了任何建议都会有所帮助,包括与原始主题无关的内容(重复的语法或其他内容)。

注意:正如我的故事所说,当内容为“1.0 0 -4.0”时,我唯一更改的是 Double.toString(x1) 为“2.0”,并且它通过了我的测试用例。

public class QuadraticFormula {
public String quadraticFormula(String content) {
//**
* content should be a string in the format of "a b c" or this will
* return an empty string.
* returning "" will indicate that content was not correctly inputted.
* returns a string in the format of "x1 and x2" where x1 and x2 are the
* answers from the Quadratic Formula.
*/
try {
int m=content.indexOf(" ");
int n=content.indexOf(" ", m+1);
if (m==-1||n==-1) {
return "";
}
double a=Double.parseDouble(content.substring(0,m));
double b=Double.parseDouble(content.substring(m+1,n));
double c=Double.parseDouble(content.substring(n+1));
if (b*b<4*a*c) {
return "imaginary";
} else {
double x1=(-b+Math.sqrt(Math.abs(b*b-4*a*c)))/(2*a);
double x2=(-b-Math.sqrt(Math.abs(b*b-4*a*c)))/(2*a);
return Double.toString(x1) + " and " + Double.toString(x2);
}
} catch (IndexOutOfBoundsException e) {
return "";
} catch (NullPointerException e) {
return "";
} catch (NumberFormatException e) {
return "";
}
}
}

最佳答案

只需使用以下代码将 double 值转换为字符串:

String doubleString=new DecimalFormat("#0.00").format(doubleValue);

DecimalFormat 来自 java.text 包。

关于java - Double.toString(2.0) 在Java中不是 "2.0"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25423188/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com