测试数字是否为另一个的倍数 [英] Test if a number is a multiple of another

查看:49
本文介绍了测试数字是否为另一个的倍数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的课本中有一个问题,说:

i have a question in my textbook that says:

编写一个以两个整数为参数的方法倍数,如果第一个整数是可整除的,则返回true均匀地分配到第二个(即除法后没有余数);否则,该方法应返回false.将此方法整合到应用程序中,该应用程序使用户能够输入值来测试方法.

并且我编写了这段代码,但是它不起作用:

and i wrote this code but its not working:

public class project1 {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int a, b;
        System.out.println("enter the first number");
        a = input.nextInt();

        System.out.println("enter the first number");
        b = input.nextInt();
    }

    public static boolean multiple(int g, int c) {

        int g, c;

        if (g % c = 0) {
            return true;
        } else {
            return false;

        };
    }
}

推荐答案

首先,您不需要声明 g c 在功能 multiple 中再次出现(这是一个错误).其次,您根本没有调用该函数,只是实现了它.与其他人一样,您需要使用 == 而不是 = .

First of all you don't need to declare g and c again in the function multiple (It is an error). Second, you didn't call the function at all, you just implemented it. And like other people answered, you need to have == instead of =.

public static void main(String[] args) {
    Scanner input = new Scanner (System.in);
    int a,b;
    System.out.println("enter the first number");
    a=input.nextInt(); 

    System.out.println("enter the first number");
    b=input.nextInt();

    boolean result = multiple(a,b);
    System.out.println(result);
}

public static boolean multiple (int g,int c){
    if (g%c==0){
        return true;
    }
    else
    {
        return false;
    }
}

请注意,您可以使用较短的 multiple 版本,其中只有一行: return g%c == 0;

Note that you can have a shorter version of multiple which have only one line: return g%c==0;

这篇关于测试数字是否为另一个的倍数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆