java 中的百分比计算结果未定义
Result is undefined for percentage calculation in java
我想计算百分比,这里的数据是完全动态的。
int sample1 = 0;
int total = 0;
int finalValue = 0;
finalValue = ((sample1*100)/total)
这里finalValue
在有数据的情况下完全按照我的意愿打印出来。但是当数据库中的值为 0(零)时,这个简单的计算就会出错。如果您在计算器中执行计算,它会显示 "Result is undefined"。所以在这种情况下,我尝试使用 if and else
条件。
if(sample1>0)
{
//execute code
}
else
{
//sample1 = 0;
}
这个逻辑在这里行不通。那么执行百分比计算的简单和首选方法是什么。
finalValue = ((sample1*100)/total)
你正在除以零。
所以你必须先检查total
。
或者,如果一些数据来自数据库,它可能是 null。
你应该先检查总数。
不允许除以零,这就是它给出错误的原因
if(total != 0)
{
//execute code
}
else
{
throw (err) ; // handle the division by zero error
}
注意:!= 表示不等于
您可以利用 double
(相对于 int
)可以表示未定义值的事实:
int sample1 = 0;
int total = 0;
double finalValue = 0;
finalValue = ((sample1 * 100) / ((double) total));
System.out.println(finalValue);
这会打印:
NaN
这是“not a number”的缩写。
我想计算百分比,这里的数据是完全动态的。
int sample1 = 0;
int total = 0;
int finalValue = 0;
finalValue = ((sample1*100)/total)
这里finalValue
在有数据的情况下完全按照我的意愿打印出来。但是当数据库中的值为 0(零)时,这个简单的计算就会出错。如果您在计算器中执行计算,它会显示 "Result is undefined"。所以在这种情况下,我尝试使用 if and else
条件。
if(sample1>0)
{
//execute code
}
else
{
//sample1 = 0;
}
这个逻辑在这里行不通。那么执行百分比计算的简单和首选方法是什么。
finalValue = ((sample1*100)/total)
你正在除以零。
所以你必须先检查total
。
或者,如果一些数据来自数据库,它可能是 null。
你应该先检查总数。
不允许除以零,这就是它给出错误的原因
if(total != 0)
{
//execute code
}
else
{
throw (err) ; // handle the division by zero error
}
注意:!= 表示不等于
您可以利用 double
(相对于 int
)可以表示未定义值的事实:
int sample1 = 0;
int total = 0;
double finalValue = 0;
finalValue = ((sample1 * 100) / ((double) total));
System.out.println(finalValue);
这会打印:
NaN
这是“not a number”的缩写。