gpt4 book ai didi

java - 我得到的分母为负数

转载 作者:行者123 更新时间:2023-12-01 13:49:04 25 4
gpt4 key购买 nike

我编写了一个程序,将两个分数相加,如果分母为 0,则应抛出 IllegalArgumentException。当我测试它时,我失败了,当我尝试添加 0/2 + -1/2 时,我应该得到 -1/2 但我得到了 1/-2,我该如何解决这个问题?

语言为德语,bruch 表示分数neuNenner 表示新分母neuZaehler 表示新分子ggtgcd

我删除了

assertEquals("Zaehler = -1 Nenner = 2",
rechnen.Rechnen.bruchAddition(0, 2, -1, 2));

但是后来我得到了这个错误java.lang.AssertionError

这是我的代码:

    public class Rechnen {

public static String bruchAddition(int z1, int n1, int z2, int n2) {

int neuZaehler = (z1 * n2) + (z2 * n1);
int neuNenner = n1 * n2;

int ggt = ggt(neuZaehler, neuNenner);
neuZaehler = neuZaehler / ggt;
neuNenner = neuNenner / ggt;

if (n1 == 0 || n2 == 0) {
throw new IllegalArgumentException();
}
return ("Zaehler = " + neuZaehler + " Nenner = " + neuNenner);

}

static public int ggt(int x, int y) {
if (y == 0) {
return x;
}
return ggt(y, x % y);
}
}

这是 JUnit 测试用例:

import static org.junit.Assert.*;
import org.junit.Test;
public class RechnenTest {
@Test
public void test() {
assertEquals("Zaehler = 1 Nenner = 1",
rechnen.Rechnen.bruchAddition(1, 3, 2, 3));
assertEquals("Zaehler = 1 Nenner = 1",
rechnen.Rechnen.bruchAddition(5, 8, 3, 8));
assertEquals("Zaehler = 1 Nenner = 1",
rechnen.Rechnen.bruchAddition(10, 16, 3, 8));
assertEquals("Zaehler = 1 Nenner = 3",
rechnen.Rechnen.bruchAddition(-1, 3, 2, 3));
assertEquals("Zaehler = -1 Nenner = 2",
rechnen.Rechnen.bruchAddition(0, 2, -1, 2));
assertEquals("Zaehler = -2 Nenner = 3",
rechnen.Rechnen.bruchAddition(-1, 3, 1, -3));
try {
rechnen.Rechnen.bruchAddition(1, 1, 1, 0);
fail();
} catch (IllegalArgumentException e) {
assertTrue(true);
}
try {
rechnen.Rechnen.bruchAddition(Integer.MAX_VALUE, 1, 1, 1);
fail();
} catch (IllegalArgumentException e) {
assertTrue(true);
}
assertEquals("Zaehler = 1 Nenner = " + Integer.MAX_VALUE,
rechnen.Rechnen.bruchAddition(0, Integer.MAX_VALUE, 1,
Integer.MAX_VALUE));
}
}

最佳答案

运算后检查分子和分母上的符号。如果它们都是负数或者分子是正数而分母是负数,则翻转两个符号。

关于java - 我得到的分母为负数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20110402/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com