Accurate Decimal/Big Number Subtraction using C

After solving decimal/big number addition, our team moved on to try to accurately subtract decimals without any errors.

Our first thoughts were to simply change the addition sign to a subtraction sign. However, this would create a wrong result if the correct result is a negative number.

One way of solving this was by adding a 1 in front of the first number when the second number is bigger. Then, subtract that number from 100. Lastly, add a negative sign in front of the result.

For example, 12 – 34. First add a 1 in front, ‘1’12 – 34 = 78. Then, subtract 78 from 100, 100 – 78 = 22. Therefore, 12 – 34 = -22.

Another way of subtracting a bigger number from a smaller number is to find the larger number; then, subtract the smaller number from the bigger number.

Below is an example code of how to find the larger number

    // offset is the left-most index of the numbers
// si is to remember which one is the bigger number, which one is the smaller number
    if (offset[0] < offset[1]) {
        si[0] = 0si[1] = 1;
    } else if (ofs[0] > ofs[1]) {
        si[0] = 1si[1] = 0;
    } else {
        // if integer part has the same length, default first – second
        si[0] = 0si[1] = 1;
        // compare each number until end of both numbers
        for (j = ofs[0]; j < ij++) {
            // skip dot
            if (j == SIZE / 2continue;
            // zero for non-numbers
            if (s[0][i] > ‘9’ || s[0][i] < ‘0’s[0][i] = ‘0’;
            if (s[1][i] > ‘9’ || s[1][i] < ‘0’s[1][i] = ‘0’;

 

            // larger digit = larger number
            if (s[0][j] > s[1][j]) break;
            if (s[0][j] < s[1][j]) {
                si[0] = 1si[1] = 0;
                break;
            }
        }
    }