所以我有一个数学方程,我需要在java中使用但由于某种原因我的代码给了我小错误:(
在额外学分
部分的this web page上描述了数学等式我目前的代码输出4000而且回答是4005我错了什么?
我的测试类看起来像这样
public class MainActivity {
public static void main(String[] args) throws Exception{
double baseMaterial =556;
int me =5;
int ml = 10;
int extraMaterial = 3444;
System.out.println(""+calculateMiniralTotal(baseMaterial,me,ml,extraMaterial));
}
public static double calculateMiniralTotal(double perfekt,int me,int ml,int extraMaterial) {
double s = (perfekt + (perfekt * (10 / (ml + 1)) / 100));
s = Math.round(s);
double r = s + (perfekt * (0.25 - (0.05 * me)));
r = Math.round(r);
double q = extraMaterial + (extraMaterial * (0.25 - (0.05 * me)));
q = Math.round(q);
//double r=q;
r = r + q;
return Math.round(r);
}
}
答案 0 :(得分:1)
您正在使用(10 / (ml + 1)) / 100
执行整数除法,在Java中必须生成另一个int
。您的ml
为10
,而在Java中,10 / 11
为0
,而非0.909
...,并且s
没有添加任何内容。
使用double
字面值或强制转换为double
来强制进行浮点计算。
double s = (perfekt + (perfekt * (10.0 / (ml + 1)) / 100));
或
double s = (perfekt + (perfekt * ( (double) 10 / (ml + 1)) / 100));
进行任何更改都会产生输出:
4005.0
答案 1 :(得分:0)
当你将一个double乘以一个int时,你会得到一个int。
public class Main
{
public static void main(String[] args)
throws Exception
{
double baseMaterial = 556;
int me = 5;
int ml = 10;
int extraMaterial = 3444;
System.out.println("" + calculateMiniralTotal(baseMaterial, me, ml, extraMaterial));
}
public static double calculateMiniralTotal(double perfekt, int me, int ml, int extraMaterial)
{
double s = (perfekt + (perfekt * (10.0 / (ml + 1)) / 100.0)); // <-- changed from 10 to 10.0 and 100 to 100.0. This way they are doubles too
s = Math.round(s);
double r = s + (perfekt * (0.25 - (0.05 * me)));
r = Math.round(r);
double q = extraMaterial + (extraMaterial * (0.25 - (0.05 * me)));
q = Math.round(q);
// double r=q;
r = r + q;
return Math.round(r);
}
}