C ++ Long Division

时间:2014-04-06 03:10:49

标签: c++

在处理我的个人项目时,我遇到了需要划分两个非常大的任意数字(每个数字大约有100个数字)。 所以我写出了非常基本的除法代码(即,答案= a / b,其中a和b由用户估算)并且很快发现它只有16位数的精度!在这一点上可能很明显,我不是编码器!

所以我在互联网上搜索并找到了一个代码,据我所知,它通过制作一个字符串来使用传统的长分割方法(但实际上我也不确定,因为我很困惑)。但是在运行代码时,它会给出一些不正确的答案,如果> b则根本不会工作。 我甚至不确定是否有比下面的代码中的方法更好的方法来解决这个问题!?也许有一个更简单的代码??

所以基本上我需要帮助来编写一个代码,用C ++来划分两个非常大的数字。 任何帮助或建议都非常感谢!

#include <iostream> 
#include <iomanip>
#include <cmath>

using namespace std;  //avoids having to use std:: with cout/cin



int main (int argc, char **argv)
{
    string dividend, divisor, difference, a, b, s, tempstring = ""; // a and b used to store dividend and divisor.
    int quotient, inta, intb, diff, tempint = 0;
    char d;

    quotient = 0;

    cout << "Enter the dividend?  ";      //larger number (on top)
    cin  >> a;
    cout << "Enter the divisor?  ";           //smaller number (on bottom)
    cin  >> b;

    //making the strings the same length by adding 0's to the beggining of string.
    while (a.length() < b.length())  a = '0'+a;          // a has less digits than b add 0's
     while (b.length() < a.length())  b = '0'+b;          // b has less digits than a add 0's

    inta = a[0]-'0';                        // getting first digit in both strings
    intb = b[0]-'0';

    //if a<b print remainder out (a) and return 0
    if (inta < intb)
    {
        cout << "Quotient: 0 " << endl << "Remainder: " << a << endl;
    }


    else
    {
        a = '0'+a;
        b = '0'+b;
        diff = intb;
        //s = b;
       // while ( s >= b )

        do
        {
            for (int i = a.length()-1; i>=0; i--)            // do subtraction until end of string
            {
            inta = a[i]-'0';                    // converting ascii to int, used for munipulation
            intb = b[i]-'0';   
            if (inta < intb)                 // borrow if needed
            {
              a[i-1]--;                         //borrow from next digit
              a[i] += 10;
            }
            diff = a[i] - b[i];
          char d = diff+'0';
           s = d + s;                           //this + is appending two strings, not performing addition.

            }
         quotient++;
         a = s;
        // strcpy (a, s);
        } 

        while (s >= b); // fails after dividing 3 x's

    cout << "s string: " << s << endl;
     cout << "a string: " << a << endl;
     cout << "Quotient:  " << quotient << endl;
     //cout << "Remainder: " << s << endl;

    }

    system ("pause");
    return 0;
    cin.get(); // allows the user to enter variable without instantly ending the program
    cin.get(); // allows the user to enter variable without instantly ending the program

}

1 个答案:

答案 0 :(得分:1)

有比这更好的方法。对于大的红利和小的除数,这种减法方法是任意慢的。规范方法在Knuth,D.E。,计算机编程的艺术,第2卷中作为算法D给出,但我确定你会在网上找到它。如果某个地方没有维基百科,我会感到很惊讶。