我有以下代码,变量s的输出始终为零:
double v = high; double s; double h;
if (v == 0) {
s = 0;
h = 0;
System.out.println("v and s and h is zeroo" + v + s + h);
} else {
s = (high - low) / high;
System.out.println("s is equal to" + s);
System.out.println("high is equal to" + high);
System.out.println("low is equal to" + low);
if (s == 0) {
h = 0;
System.out.println("high and low are equals" + high + "==" + low);
} else {
double alpha;
alpha = 60 * (mid - low) / (high - low);
System.out.println("alpha is : " + alpha);
}
}输出示例:
s is equal to0.0
high is equal to139
low is equal to30
high and low are equals139==30发布于 2014-09-26 19:16:17
由于high和low都属于int类型,因此s = (high-low)/high行中的除法使用整数除法,并且由于high - low将始终小于high (除非low为负数),因此结果将始终为零。
要解决此问题,请将其中一个转换为double:
s = (high-low)/(double)high;发布于 2014-09-26 19:13:07
仅仅将变量定义为整数类型并不意味着操作本身将是双精度的,高和低是139和30,这是整数,而Integer/Integer是一个双精度整数,然后将其扩展为双精度(即,.0.0)
只需将高或低转换为双精度,您将获得双精度的结果
s= (high-low)/(double)high;发布于 2014-09-26 19:15:20
由于high和low是整型,因此
(high-low)/high是作为int值计算的。
尝试:
1.0*(high-low)/highhttps://stackoverflow.com/questions/26058140
复制相似问题