2 messages
Open this post in threaded view
|

 I used my Jack files to do the tests, and the following problems occurred when testing stringtest. Later I found out that the problem was math. VM because I used the math. VM provided by the system to do the test, no problem, once I changed to my own math. vm, there are more problems. The problem should be in -32767 and -32123 because they exceed the 16 digit range. So display errors. How should I deal with this problem? 以下是我相关的代码 ```     /** Sets this string to hold a representation of the given value. */     method void setInt(int n) {         let len = 0;         if (n < 0) {             let n = -n;             do appendChar(45);         }         do setInt2(n);         return;     }     method void setInt2(int n) {         var int nextN;         if (n < 10) {             do appendChar(String.d2c(n));         } else {             let nextN = n / 10;             do setInt2(nextN);             do appendChar(String.d2c(n - (nextN * 10)));         }         return;     }      function int multiply(int x, int y) {         var int sum, index, mask;         let mask = 1;         while (index < 16) {             if (y & mask) {                 let sum = sum + x;             }             let x = x + x;             let index = index + 1;             let mask = mask + mask;         }         return sum;     }     function int divide(int x, int y) {         var int q;         if (y = 0) {             do Sys.error(3);             return 0;         }         let q = Math._div(Math.abs(x), Math.abs(y));         if ((x < 0) = (y < 0)) {             return q;         } else {             return -q;         }     }     function int _div(int x, int y) {         var int q, result, sum;         if ((y > x) | ~(y < 16384)) {             return 0;         }         let q = Math.divide(x, y + y);         let sum = q + q;         if ((x - (sum * y)) < y) {             let result = sum;         } else {             let result = sum + 1;         }         return result;     } ```
Open this post in threaded view
|

 Administrator Both these are legal 16-bit 2's complement numbers. -32767 = 1000 0000 0000 0001 -32123 = 8000 0010 1000 0101 The problem is likely in your Math.divide.  The provided algorithm for divide has this line:     q = divide(x, 2*y) and the problem is that 2*y can be too big for 16-bit signed ints. you need to prevent this call if y is too big. ``` if (y < 16384) { q = Math.divide (x, y+y); // 2*y is OK to compute } else { q = 0; // 2*y is greater than any possible x, q must be 0 } ```