Java将int转换为double
我试图让java在用户输入1、2和5时输出类似于2.66的内容。但是,它只打印2.00。我怎样才能解决这个问题Java将int转换为double,java,Java,我试图让java在用户输入1、2和5时输出类似于2.66的内容。但是,它只打印2.00。我怎样才能解决这个问题 public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Please input first integer: "); int a = in.nextInt(); System.out.print("Please i
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please input first integer: ");
int a = in.nextInt();
System.out.print("Please input second integer: ");
int b = in.nextInt();
System.out.print("Please input third integer: ");
int c = in.nextInt();
float calculateInput = (float)((a+b+c)/3);
System.out.printf("The average of %s, %s, and %s is %.2f \n", a, b, c, calculateInput);
double e = (double)(1+2+5)/3;
System.out.print(calculateInput);
}
试试这个
(float)(a+b+c)/(float)3代码>或双e=(双)(1+2+5)/(双))3
通过在(float)((a+b+c)/3)
中的数学表达式周围添加括号,可以确保在转换为float之前完成整数除法。去掉外圆括号,只需执行(浮点)(a+b+c)/3
。这将使a、b和c的总和浮动,然后除以3。