JAVA作业问题

指着太阳说日

够硬, 才能撑起爱
VIP
注册
2005-09-21
消息
8,913
荣誉分数
460
声望点数
0
1. Write a method for a class called BallPacker that prompts for three ints (one at a time) representing the dimensions of a box and a float that represents the radius of a ball. Then compute the number of balls that would fit in the box. Display the results in the Java console. Be sure to test your code with many different box and ball sizes. Assume that the balls are only stacked on top of each other neatly (shown bellow).
 
import java.util.Scanner;
public class BallPacker {
public static void main (String args[]) {
int l, w, h;
float r, number;
Scanner keyboard = new Scanner(System.in);

System.out.println("Enter the parameter(Length, Weight, High, and Radius):");
l = keyboard.nextInt();
w = keyboard.nextInt();
h = keyboard.nextInt();
r = keyboard.nextFloat();

number = l * w * h / 8 / r / r / r;
//compute the number of balls and store it
if ((l < 2 * r)||(w < 2 * r)||(h < 2 * r)){
System.out.println("Error:Invalid index");
}
else{

System.out.println("Given parameter of length, weight, high and radius are " + l + ", " + w + ", " + h + ", and " + r);
System.out.printf("The number of the balls is " + number);
}
}

}
 
问题就是 如果输入的radius是带小数的话

number最后就也带小数了 ....... 怎样让NUMBER四舍五入得个整数啊 ?~
 
Re: 为啥

最初由 xiaoxiaomajia 发布


不来问阿?

1。这里又不是作业辅导区
2。这题这么简单


BTW, number = (l / 2r) * (w /2r ) * (h/ 2r)
 
dude ... read teh lecture note ...
 
Re: Re: 为啥

最初由 signup2banned 发布


1。这里又不是作业辅导区
2。这题这么简单


BTW, number = (l / 2r) * (w /2r ) * (h/ 2r)

我想问的是怎样把结果约成个整数 ...
 
用Math.round()这个function就搞定了,
把result放到()里面就行
 
真JB笨, number = Math.round(l /2 /r) * Math.round( w /2/ r ) * Math.round(h /2 /r)

最初由 指着太阳说日 发布
number = Math.round(l * w * h / 8 / r / r / r)


谢撩 ~
 
number = Math.round(l /2 /r) * Math.round( w /2/ r ) * Math.round(h /2 /r)

should use number=math.floor(L/2r)*math.floor(W/2r)*math.floor(H/2r)
 
Re: number = Math.round(l /2 /r) * Math.round( w /2/ r ) * Math.round(h /2 /r)

You are probably right, I don't know what round do, I supposed 黄昏 provided the right function

最初由 ceres 发布
should use number=math.floor(L/2r)*math.floor(W/2r)*math.floor(H/2r)
 
后退
顶部