所以在我最後一個問題的代碼中有一個錯誤。我試圖修改應該添加兩個大數字作爲兩個數組的代碼(我不能使用BigIntiger,我必須自己創建該方法)。但它仍然給我錯誤的結果。添加兩個大數字pt.2
例如(我已經有這樣做的構造函數):
BigNumber dl1 = new BigNumber(1500);
BigNumber dl2 = new BigNumber("987349837937497938943242");
dl3 = dl1.add(dl2);
System.out.println("Result: " + dl3);
它給了我6575這是錯誤的結果。
public BigNumber add(BigNumber num2){
char[] m = null;
long y = 0;
long x = 0;
boolean tmpBool = false;
boolean leftIsBigger = false;
String tmpString = "";
int ending = 0;
if (this.n.length >= num2.n.length){
m = new char[this.n.length + 1];
y = num2.n.length;
x = this.n.length;
leftIsBigger = true;
}
else{
m = new char[this.n.length + 1];
y = this.n.length;
x = num2.n.length;
}
for(int i = 0; i < y; i++){
int left = 0;
if(leftIsBigger) left = Character.getNumericValue(this.n[i]);
else left = Character.getNumericValue(num2.n[i]);
for(int j = 0; j < y; j++){
int right = 0;
if(!leftIsBigger) right = Character.getNumericValue(num2.n[j]);
else righta = Character.getNumericValue(this.n[j]);
int z = left + right;
if(tmpBool){
z++;
tmpBool = false;
}
if(z > 9){
tmpBool = true;
z = z%10;
}
m[i] = Character.forDigit(z, 10);
}
ending++;
}
for(int k = ending; k < m.length - 1; k++){
if (leftIsBigger){
if (tmpBool){
int c = Character.getNumericValue(this.n[k]);
if (c > 9){
tmpBool = true;
c = c%10;
m[k] = Character.forDigit(c, 10);
}
else{
tmpBool = false;
m[k] = Character.forDigit((c+1), 10);
}
}
else
m[k] = this.n[k];
}else{
if (tmpBool){
int c = Character.getNumericValue(liczba2.n[k]);
if (c > 9){
tmpBool = true;
c = c%10;
m[k] = Character.forDigit(c, 10);
}
else{
tmpBool = false;
m[k] = Character.forDigit((c+1), 10);
}
}
else
m[k] = this.n[k];
}
}
for (int it = m.length - 1; it >= 0; it--){
tmpString += m[it];
}
BigNumber dl = new BigNumber(tmpString);
return dl;
}
*爲什麼*你不能使用BigIntegers?它是在標準的Java SE中,爲什麼重新發明輪子? – Ingo
你在'else righta = Character.getNumericValue(this.n [j])中有一個拼寫錯誤',但這可能不是你的問題。 –
**編輯**:關於長度檢查,沒關係檢查BigInteger源。你的課程看起來有點冗長。什麼是'BigNumber.n'? – Gorbles