整数分区的Java剩余部分?

问题描述 投票:6回答:4

我正在四处寻找这个话题,但我仍然没有得到它,如果有人可以详细说明,我会非常感激。

我的任务是将两个变量除以整数除以余数。问题是,我不知道余数是什么,现在我做了类似的事情,这是我通过互联网搜索找到的:

int a;
int b;
int remainder = Math.Pow(a,2) % b;

System.out.println("a^2 / b = " + Math.Pow(a,2) / b);
System.out.println("remainder = " + remainder);

如果我例如设置(a = 43)和(b = 67)

然后我会得到这个结果:

a^2 / b = 27
remainder = 40

现在因为我不知道剩下的是什么(这只是互联网上的一个建议)我不知道这是否是正确的答案..?

谢谢你的帮助,

亲切的问候

java math divide
4个回答
12
投票

如果您正在寻找可以使用的数学模运算

int x = -22;
int y = 24;
System.out.println(Math.floorMod(x, y));

如果你对数学模数(只是余数)不感兴趣那么你可以使用

int x = -22;
int y = 24;
System.out.println(x%y);

2
投票
    public static void main(String[] args) {
        int dividend = 139, divisor = 7;

        int quotient = dividend / divisor;
        int remainder = dividend % divisor;

        System.out.println("The Quotient is = " + quotient);
        System.out.println("The Remainder is = " + remainder);
    }

输出:

商数= 19

剩余是= 6


1
投票

是的,%运算符将返回整数除法的余数。

要了解有关整数分区剩余部分的更多信息,请查看Wikipedia

如果a和d是整数,d非零,则可以证明存在唯一的整数q和r,使得a = qd + r且0≤r<| d |。数字q称为商,而r称为余数。


0
投票

int remainder = a % b;会对你进行排序。余数运算符返回除法的余数。


请注意,余数运算符也称为模运算符。但是,对于Java来说这是不正确的,因为如果左操作数a为负,Java将返回负值。


0
投票

%运算符将返回整数除法的余数。

引擎盖下实际上有哪些模块?

模块倾向于从数字中删除cycles,直到它达到一个正数,这个数字小于我们称之为模数OR的循环数,我们称之为reminder

但是,使用%运算符的时间非常昂贵。

为避免在获得相同结果时使用%,我们可以使用以下内容:

  • While(a >= n) a -= n;(当a为正数时)
  • While(a < 0) a += n;(当a为负数时)
  • a = n*q + r,这意味着r = a - n*qq is the integer division of a/n这意味着a%n == a - n * Math.toIntExact(a/n)a是一个正数时这是足够的。
  • 虽然a是负数,但我们可以使用(a%n + n) % n,它将为您提供模块。

时钟案例场景:

如果它现在是9点钟,4小时后的时间=> 9 + 4 = 13h => 13%12 = 1 while 12 is the cycle number in the clock

如果我们需要在24小时(昨天)之前计算时间,那么是9 O'clock,那么:24(2*12) =>昨天意味着9-24 = -15h虽然正确的答案是9,为了解决这个问题我们将使用(a%n + n) % na%n == (a - n * Math.toIntExact(a/n))然后-15 - 12 * Math.toIntExact(-15/12) = -3 => -3 + 12 = 9 => 9%12 => 9 - 12 * Math.toIntExact(9/12) = 9这是正确的答案。

这是时钟场景的代码:

public static void main(String args[]){
    Scanner scanner = new Scanner(System.in);
    int a = scanner.nextInt(); // a = -15
    int n = scanner.nextInt(); // cycle = 12

    int reminder = a - (n * Math.toIntExact(a / n));
    int reminder_plus_n = (reminder + n);
    int modulo = reminder_plus_n - (n * Math.toIntExact(reminder_plus_n / n));
    System.out.println(modulo); // Answer = 9
} 
© www.soinside.com 2019 - 2024. All rights reserved.