计算所需的比萨饼数量并切片剩余

时间:2017-01-23 02:58:41

标签: java

我需要帮助弄清楚如何修改我的程序来计算所需的比萨饼数量,然后计算切片的剩余部分。因此,例如,如果用户输入18个人,则需要2个比萨饼(因为每个披萨有20个切片),剩下4个切片。每个披萨的切片和每个人吃多少切片是恒定的,每人2片,每披萨20片。该计划要求参加的人数。我也不能使用条件语句。

`

    int pizza = 20;
    int pizzaperson = 2;


    System.out.println("What is the number of people expected at the pizza party?");
    int people = Integer.parseInt(s.nextLine());


    int pizzatotal = (people * pizzaperson);
    int pizzaleft = pizzatotal % pizza; 
    int total = (pizza / pizzaperson) % people;
            System.out.println("For " + people + " people that would be " + pizzatotal + " pizza(s) with each person having " + pizzaperson + " slices each.");
            System.out.println("There would be " + pizzaleft + " slice(s) leftover");

`

1 个答案:

答案 0 :(得分:0)

只需找到所需的比萨饼数量,然后用它来查找剩余比萨饼的数量。

int SLICES_PER_PIZZA = 20;
int SLICES_PER_PERSON = 2;

System.out.println("What is the number of people expected at the pizza party?");
int people = Integer.parseInt(s.nextLine());
int slices = people * SLICES_PER_PERSON;

int num_pizzas = (slices + SLICES_PER_PIZZA - 1) / SLICES_PER_PIZZA; // round up
// Alternatively, you can use Math.ceil:
// int num_pizzas = (int) Math.ceil(1.0 * slices / SLICES_PER_PIZZA); // round up
int remainder = (num_pizzas * SLICES_PER_PIZZA) - slices; 

System.out.println("For " + people + " people that would be " + num_pizzas + " pizza(s) with each person having " + SLICES_PER_PERSON + " slices each.");
System.out.println("There would be " + remainder + " slice(s) leftover");