Java静态值不输出小数“;从double到int的可能有损转换;
您好,我对java非常陌生,现在才3天,我正在努力让这个程序输出小数Java静态值不输出小数“;从double到int的可能有损转换;,java,Java,您好,我对java非常陌生,现在才3天,我正在努力让这个程序输出小数 static int temp1=66-32*(5/9); static int temp2=95-32*(5/9); static int temp3=85-32*(5/9); static int temp4=65-32*(5/9); static int temp5=(0-32)*(.55); public static void main(String[] args) { System.out.pri
static int temp1=66-32*(5/9);
static int temp2=95-32*(5/9);
static int temp3=85-32*(5/9);
static int temp4=65-32*(5/9);
static int temp5=(0-32)*(.55);
public static void main(String[] args) {
System.out.println("Today's temperature is 66 degrees Fahrenheit. In Celsius it is:"+temp1);
System.out.println("The temperature is 95 degress Fahrenheit in Celsius is:"+temp2);
System.out.println("The temperature is 85 degrees Fahrenheit in Celsius is:"+temp3);
System.out.println("The temperature is 65 degrees Fahrenheit in Celsius is:"+temp4);
System.out.println("The temperature is 0 degrees Fahrenheit in Celsius is:\n"+temp5);
}
您正在使用整数。整数不能显示小数。试着用double代替。Double最多可提供16位精度
static double yourTemp = ...
5/9==0
在整数除法中,5除以9等于零
你的公式也不正确。您需要先执行-32
int temp1 = (66-32) * 5 / 9;
这将为您提供向下舍入的最接近的整数值
double temp1 = (66 - 32) * 5 / 9.0;
// print temp1 to two decimal places.
System.out.printf("Temp1= %.2f%n", temp1);
这将给您两位小数。使用/9.0
意味着使用浮点除法,因为9.0
是一个双精度值。到目前为止,没有什么区别,但你可以写
double temp1 = (66.0 - 32.0) * 5.0 / 9.0;
并得到相同的结果。首先,如果要接收十进制输出,必须将数据类型从
int
更改为double
,因为double
是用于将变量声明为持有十进制值的数据类型。因此,将所有的int
更改为double
秒:您认为(5/9)应该输出0.555左右的值,对吗?因为这就是你在计算器上输入的结果。但是没有!在Java中,(5/9)作为整数转换计算,因为5和9都是整数。这意味着,当Java计算(5/9)时,它只返回小数点左边的数字,因为它知道不处理小数。0.555中小数点的左边是多少?显然,0。因此,(5/9)返回的答案将是0,这意味着你的temp1
,temp2
,temp3
,和temp4
都将是0,因为0乘以任何值都是0。对于temp5
,您在.55中包含了小数点-因此,此计算是正确的
所以。。。什么?如果您想在屏幕上打印十进制答案,您可以执行以下两种操作之一:在每个数字的末尾添加一个小数点。因此,将其设置为66.0-32.0*(5.0/9.0)
。或者,您可以简单地向(5/9)中添加一个(双)
强制转换。比如:((双精度)5/9)
。请确保完全按照给定的格式格式化,否则它将无法工作,您可能仍然会得到0。下面是完成的代码:
public class printDecimal{
static double temp1 = 66-32 * ((double)5/9);
static double temp2 = 95-32 * ((double)5/9);
static double temp3 = 85-32 * ((double)5/9);
static double temp4 = 65-32 * ((double)5/9);
static double temp5 = (0-32) * ((double)5/9);
public static void main(String[] args){
System.out.println("66 degrees Fahrenheit in Celsius is: "+temp1);
System.out.println("95 degrees Fahrenheit in Celsius is: "+temp2);
System.out.println("85 degrees Fahrenheit in Celsius is: "+temp3);
System.out.println("65 degrees Fahrenheit in Celsius is: "+temp4);
System.out.println("0 degrees Fahrenheit in Celsius is: "+temp5);
}
}
double最多提供16位精度,可能超过16位小数。您可以更正您的答案,我将删除我的评论。