[英]Loop is turning my negative integer positive in java
Java中的這段代碼似乎使我的負整數變為正數。 我傳入-9和1,然后在調試器中,第一個for循環中的i從27開始而不是負27。更奇怪的是,如果我添加一行使i = -1,它將切換永遠在-27到-28之間。 有人可以告訴我為什么嗎?
我輸入的是-9,1。結果應該是可被3整除的數字和模數為5。我認為-29滿足此條件。
public static int getIntegerH(int x, int y) {
System.out.println("The result of the getIntegerH method:");
boolean flag = true;
int n = x * 4; // 36
int m = x * 3; // 27
if (x == y) {
flag = true;
}
if (x < 0 || y < 0) {
for (int i = -m; i < -n; i++) {
if (i / 3 == x && i % 5 == y ) {
System.out.println(i);
flag = false;
}
}
} else if (x > 0 || y > 0) {
for (int i = m; i < n; i++) {
if (i / 3 == x && i % 5 == y ) {
System.out.println(i);
flag = false;
}
}
}
if (flag == true) {
System.out.println("No such number");
}
return 0;
}
您將i設置為m的負數。
for (int i = -m; i < -n; i++) {
如果您為x傳遞了-9,則m為-27,-27的負值為27。
作為附帶說明,您還需要查看您的狀況和增量。 如果您想從-27倒數到-36,您將需要以下內容:
for (int i = m; i >= n; --i ) {
這是一個適合您的解決方案,可以使用您喜歡的任何除數或模數:
final static int DIV = 3;
final static int MOD = 5;
/** Returns an integer `r` such that `r / DIV = x` and `r % MOD = y`, else returns 0 */
public static int getIntegerH(int x, int y) {
if (y >= MOD) {
System.out.println(
"getIntegerH(" + x + ", " + y + ") -> none; impossible to have a remainder of " + y
+ " when the modulo is " + MOD);
return 0;
}
// determine the min and max numbers inclusive where n / DIV = x
int min = x > 0 ? x * DIV : x * DIV - DIV + 1;
int max = x > 0 ? x * DIV + DIV - 1 : x * DIV;
// get the min and max values of the mod for this
int minMod = min % MOD;
int maxMod = max % MOD;
if ((MOD > DIV) && (y < minMod || y > maxMod)) {
System.out
.println("getIntegerH(" + x + ", " + y + ") -> none; there is no number `n` between "
+ min + " and " + max + " where `n % " + MOD + " = " + y + "`");
return 0;
}
int r = (x > 0) ? min + y - minMod : max + y - maxMod;
System.out.println("getIntegerH(" + x + ", " + y + ") -> " + r + "; " + r + " / " + DIV + " = ["
+ (r / DIV) + "]; " + r + " % " + MOD + " = [" + (r % MOD) + "]");
return r;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.