[英]java long variable behaving like int variable
我認為“長”類型變量的行為類似於“ int”類型變量。 我認為是這種情況,因為隨着變量變得越來越大,當它試圖超過2147483647(這是“ int”類型的最大值)時,它實際上會翻轉為負數。 顯然,“長”類型的最大值要寬容得多。
我想我應該在這里粘貼我的代碼。 請不要苛刻代碼,它根本沒有重構。 另外,您會看到許多la腳的嘗試,迫使代碼將我所討論的變量視為“長整型”類型,但是這些努力的總體效果並不理想。
注意,此代碼處理“ N選擇X”或組合。 輸入的是組合數和N。代碼循環遍歷X的可能值,直到找到匹配項或直到超過匹配的可能性為止(或直到計算出的組合“為負”為止)。
先謝謝您的幫助。
public class primativeLongPractice {
private static long fctrl (long num) {
long ans = 1L;
for (long i=num; i>0; i--) ans = ans * i;
return ans;
}
private static long nchoosex (long n, long x) {
long y = n - x;
if (y>x) {
long temp = y;
y=x;
x=temp;
}
long ans = 1L;
for (long i=n; i>x; i--) ans = ans * i;
return ans/fctrl(y);
}
public static long checkchoose(long m, int n) {
long N = (long)n;
long combos = 0L;
long x = 1L; // starting out at 1 and going up
// compute "n choose x" call it combos
combos = nchoosex(N,x);
System.out.println(n + " choose " + x + " equals " + combos + "; m equals " + m);
if (combos==m) return x;
while ((combos>1)&&(combos<m)) {
x = x + 1;
combos = nchoosex(N,x);
System.out.println(n + " choose " + x + " equals " + combos + "; m equals " + m);
if (combos==m) return x;
}
System.out.println("Didn't find anything");
return -1L;
}
public static void main(String[] args) {
long p = 155117520L;
int q = 30;
long r = checkchoose(p,q);
System.out.println("For inputs " + q + " and " + p + " the function returned " + r);
}
}
我很快調試了它。
對於n = 30, x = 14
您的值ans
長時間溢出並產生值
ans = -5769043765476591616
和
fctrl(y) = 87178291200
這使得結果似乎由於整數溢出而滾動。
long
int
確實比int
更具兼容性,但它仍然可能溢出。
我在您的代碼中添加了一些額外的打印以顯示問題:
private static long fctrl(long num) {
long ans = 1L;
for (long i = num; i > 0; i--) {
// Are we going tyo overflow?
if (ans * i < 0) {
System.out.println("fctrl overflow!!! " + ans + " at " + i);
}
ans = ans * i;
}
return ans;
}
private static long nchoosex(long n, long x) {
long y = n - x;
if (y > x) {
long temp = y;
y = x;
x = temp;
}
long ans = 1L;
for (long i = n; i > x; i--) {
if (ans * i < 0) {
System.out.println("nchoosex overflow!!! " + ans + " at " + i);
}
ans = ans * i;
}
return ans / fctrl(y);
}
public static long checkchoose(long m, int n) {
long ln = (long) n;
long combos = 0L;
long x = 1L; // starting out at 1 and going up
// compute "n choose x" call it combos
combos = nchoosex(ln, x);
System.out.println(n + " choose " + x + " equals " + combos + "; m equals " + m);
if (combos == m) {
return x;
}
while ((combos > 1) && (combos < m)) {
x = x + 1;
combos = nchoosex(ln, x);
System.out.println(n + " choose " + x + " equals " + combos + "; m equals " + m);
if (combos == m) {
return x;
}
}
System.out.println("Didn't find anything");
return -1L;
}
public void test() {
System.out.println("Hello");
long p = 155117520L;
int q = 30;
long r = checkchoose(p, q);
System.out.println("For inputs " + q + " and " + p + " the function returned " + r);
}
它打印
nchoosex溢出!!! 745747076954880000在17
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.