如何在java中获取余数

时间:2014-11-15 16:21:02

标签: java

学生会正在组织学生旅行,他们正在确定需要多少辆汽车。 提示用户输入旅行中的学生总数。 然后确定需要多少辆汽车(5辆车)以及没有交通工具的学生数量。

import java.util.Scanner;

class P2Trip
{
public static void main(String []args)
{
    Scanner input = new Scanner(System.in);

    int students;
    int space = 5;
    int sum;

    System.out.println("How many students are going today?: ");
    students = input.nextInt();

    sum =(students / space);
    System.out.println("Ammount of cars needed: " + sum);

 }
}//code works fine, but im not sure how to get a remainder of students without a lift.

4 个答案:

答案 0 :(得分:2)

从你的评论中,看起来你只需要帮助一个没有车的人。您需要使用百分号(%)来使用模块化部门(有些人称之为余数)。以下是您缺少的代码行:

System.out.println("Amount of people without a car: "+students%sum);

该计划的完整代码是:

import java.util.Scanner;
public class Solution {
    public static void main(String[] args) [
        Scanner s=new Scanner(System.in);
        int carCapacity=5;

        System.out.println("How many students?");
        int students=s.nextInt();
        int cars=students/carCapacity;
        int leftOver=students%carCapacity;

        System.out.println("Cars needed: "+cars);
        System.out.println("Students left over: "+leftOver);


    }
}

答案 1 :(得分:0)

答案 2 :(得分:0)

在我看来,您可以在程序中进行两项更正:

sum = (student/space);
int leftstudent;`
leftstudent=(students%space);
System.out.println("left students without transport are " +leftstudent);

答案 3 :(得分:0)

您可能希望使用Java检查模块化除法运算符。

分部/除数= 系数

Division%Divisor = 余数

例如,要查找剩余的数字学生,您必须使用“%”。