将整数除以 12 并显示余数是奇数还是偶数

尝试创建一个程序,要求用户输入 20 到 100 之间的数字。输入数字后。程序会将输入的数字除以 12。然后程序会说明除法的结果是偶数还是奇数。(例如:35除以12的余数是11,是奇数。)


我已经启动了程序,但无法弄清楚除法部分。


import java.util.Scanner;


public class Chpt3_Project {

    public static void main (String [] args) {

        // Create a Scanner object

        Scanner sc = new Scanner(System.in);


        // Prompt the user to enter an integer value between 20 and 100.

        int input;

        do {

            System.out.print("Enter a number between 20 and 100: ");

            input = sc.nextInt();


            if (input < 20 || input >= 101) {

                System.out.println("Invalid number input!");

            }

        } while (input < 20 || input >= 101);


        //Divide result by 12 and show if even or odd


    }


}


米脂
浏览 230回答 2
2回答

呼唤远方

您可以使用模运算符来检查数字是偶数还是奇数。假设你有int n = 7;应用模运算符int r = n % 2;会屈服1- 发生的事情是这样的:除以n通过2并返回其余部分。所以,我们知道如果一个% 2操作的余数是0,这个数是偶数,否则,如果余数是1,这个数是奇数。在您的情况下,代码可能如下所示:public static void main (String [] args) {&nbsp; &nbsp; // Create a Scanner object&nbsp; &nbsp; Scanner sc = new Scanner(System.in);&nbsp; &nbsp; // Prompt the user to enter an integer value between 20 and 100.&nbsp; &nbsp; int input = 0;&nbsp; &nbsp; do {&nbsp; &nbsp; &nbsp; &nbsp; System.out.print("Enter a number between 20 and 100: ");&nbsp; &nbsp; &nbsp; &nbsp; input = sc.nextInt();&nbsp; &nbsp; &nbsp; &nbsp; if (input < 20 || input >= 101) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Invalid number input!");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; } while (input < 20 || input >= 101);&nbsp; &nbsp; // Divide the input by 12 and check if the remainder is an even number (== 0).&nbsp; &nbsp; boolean isEven = (input % 12) % 2 == 0;&nbsp; &nbsp; if(isEven) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Input is an even number.");&nbsp; &nbsp; }&nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Input is an odd number.");&nbsp; &nbsp; }}

倚天杖

为了进行数学运算,您必须首先检索N mod(12)模除的结果,然后检查余数是否可被 2 -> ((N mod(12) mod(2))整除。int remainderAfterDivisionByTwelve = n % 12; // n = 35 -> results in 11boolean isRemainderEven = (remainder % 2) == 0; // remainder = 11 -> results in (1 == 0) false
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java