java中如何确定数字的倍数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3900184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 06:31:36  来源:igfitidea点击:

how to determine the multiples of numbers in java

java

提问by ays

read 2 numbers and determine whether the first one is a multiple of second one.

读取 2 个数字并确定第一个数字是否是第二个数字的倍数。

采纳答案by Martijn Courteaux

if (first % second == 0) { ... }

回答by codaddict

A number xis a multiple of yif and only if the reminder after dividing xwith yis 0.

一个数字x是的倍数y当且仅当分割后的提醒xy0

In Java the modulus operator(%) is used to get the reminder after the division. So x % ygives the reminder when xis divided by y.

在 Java 中,取模运算符 ( %) 用于获取除法后的提醒。所以除以x % y时给出提示。xy

回答by Erica

Given that this is almost certainly a homework question...

鉴于这几乎肯定是一个家庭作业问题......

The first thing you need to think about is how you would do this if you didn't have a computer in front of you. If I asked you "is 8 a multiple of 2", how would you go about solving it? Would that same solution work if I asked you "is 4882730048987" a multiple of 3"?

您需要考虑的第一件事是,如果您面前没有计算机,您将如何做到这一点。如果我问你“8 是 2 的倍数”,你会怎么解决?如果我问你“4882730048987”是 3 的倍数,同样的解决方案会起作用吗?

If you've figured out the math which would allow you to get an answer with just a pen and paper (or even a pocket calculator), then the next step is to figure out how to turn that into code.

如果您已经弄清楚了可以让您只用笔和纸(甚至是袖珍计算器)得到答案的数学方法,那么下一步就是弄清楚如何将其转化为代码。

Such a program would look a bit like this:

这样的程序看起来有点像这样:

  • Start
  • Read in the first number and store it
  • Read in the second number and store it
  • Implement the solution you identified in paragraph two using the mathematical operations, and store the result
  • Print the result to the user.
  • 开始
  • 读入第一个数字并存储
  • 读入第二个数字并存储
  • 使用数学运算实现您在第二段中确定的解决方案,并存储结果
  • 将结果打印给用户。

回答by ayush

//To check if num1 is a multiple of num2

    import java.util.Scanner;

    public class multiples {

        public static void main(String[] args) {

            Scanner reader = new Scanner(System.in);
            System.out.println("Enter a number!");
            int num1 = reader.nextInt();
            reader.nextLine();
            System.out.println("Enter another number!");
            int num2 = reader.nextInt();

            if ((num1 % num2) == 0) {
                System.out.println("Yes! " + num1 + " is a multiple of " + num2 + "!");
            } else {
                System.out.println("No! " + num1 + " is not a multiple of " + num2 + "!");
            }
            reader.close();
        }
    }