如何知道一个数是否是另一个数的倍数?

发布于 2024-09-28 07:17:05 字数 51 浏览 0 评论 0原文

我尝试使用 6%2,但它总是给出 2 而不是 0 的值。为什么以及如何才能解决这个问题?

I tried using 6%2, but its always giving the value as 2 and not 0. Why and how can I get a solution to this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

别低头,皇冠会掉 2024-10-05 07:17:05
if(!(y%x))
{
...
}

在您的情况下 !(6%2) 将返回 true

(答案与问题中的原始答案非常相似)

if(!(y%x))
{
...
}

In your case !(6%2) would return true.

(Answer very similar to the original in the question)

笑梦风尘 2024-10-05 07:17:05

我假设您想找出对于给定的 X,Y=kX 是否具有 k 的整数值,以便 Y=5, X=3 失败(k 为 5/3),但 Y=6, X=2 通过(k 恰好为 3)。您很高兴 k 是正数或负数。

这样,使用 Y 余数 X == 0 就是一个很好的测试。顺便说一句,要小心负余数(例如,Y % 2 == 1 作为奇数测试对于负数失败,请使用 Y % 2 != 0 来确保)

Java 中的代码示例

public class Example {

  public static void main(String[] args) {
    System.out.println(isIntegerFactor(5,3));  // k is not an integer
    System.out.println(isIntegerFactor(6,3));  // k is 2
    System.out.println(isIntegerFactor(-6,-3)); // k is 2 
    System.out.println(isIntegerFactor(-6,3)); // k is -2
    System.out.println(isIntegerFactor(6,-3)); // k is -2
  }

  public static boolean isIntegerFactor(int y, int x) {
    return (y % x) == 0;
  }

}

I'm asuming that you want to find out if Y=kX has integer values of k for a given X so that Y=5, X=3 fails (k is 5/3), but Y=6, X=2 passes (k is exactly 3). You are happy that k is either positive or negative.

That way, using Y remainder X == 0 is a good test. As an aside, be careful of negative remainders (e.g. Y % 2 == 1 as a test for oddness fails for negative numbers, use Y % 2 != 0 to be sure)

Code example in Java

public class Example {

  public static void main(String[] args) {
    System.out.println(isIntegerFactor(5,3));  // k is not an integer
    System.out.println(isIntegerFactor(6,3));  // k is 2
    System.out.println(isIntegerFactor(-6,-3)); // k is 2 
    System.out.println(isIntegerFactor(-6,3)); // k is -2
    System.out.println(isIntegerFactor(6,-3)); // k is -2
  }

  public static boolean isIntegerFactor(int y, int x) {
    return (y % x) == 0;
  }

}
荒人说梦 2024-10-05 07:17:05
bool prime = PrimeTool.IsPrime(input_Number);
        if (!prime)
        {
            Console.Write("multiple of other number");
            Console.WriteLine(i);
        }
bool prime = PrimeTool.IsPrime(input_Number);
        if (!prime)
        {
            Console.Write("multiple of other number");
            Console.WriteLine(i);
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文