高精度计算篇2

本来今天是写了乘法的,可是突然发现昨天的代码有问题,根本就是错误的,在于计算的方向性,这里模拟真实的算术计算,接收数据应该反过来,如12345,接收过来加入正常接收低位是1,可是实际中应该是高位,不然如果有进位就没办法处理了,所以我们要将数据逆向接收!修改后的代码可以正常运行,看上去也还是很没水平,不过加油,不要紧,慢慢来!

//工程——高精度算术计算by iwaich——2009/10/12
#include <iostream>
#include <string>
using namespace std;
#define MAX 1000


int main()
{
    int num1[MAX]={0};
    int num2[MAX]={0};
    int num3[MAX]={0};
    memset(num1,0,sizeof(num1));
    memset(num2,0,sizeof(num2));
    memset(num3,0,sizeof(num3));
    int strenth1;
    int strenth2;
    string fn;
    string sn;
    cout<<"Please input two number for Adding !"<<endl;
    cin>>fn>>sn;

    strenth1=fn.length();
    strenth2=sn.length();

    for(int i=0, j=strenth1;i<strenth1;i++,j--)
    {
        num1[i]=fn[j-1]-'0';
    }
    for(int i=0, j=strenth2;i<strenth2;i++,j--)  //不能定义像这样int i=0,int j=strenth2;
    {
        num2[i]=sn[j-1]-'0';
    }
    cout<<num1<<endl<<num2<<endl;    //想这样输出数组是不行的,只用char型用数组名输出,int型由于int占4个字节所以,这样 只会输出地址!
    getchar();

    int add_length=(strenth1>strenth2?strenth1:strenth2);
    int i;

    for(i=0;i<add_length;i++)
    {
        num3[i]=num3[i]+num2[i]+num1[i];
        num3[i+1]=num3[i]/10;
        num3[i]=num3[i]%10;
    }
    if(num3[i]==1)
    {
        i=i+1;
    }
    int j;
    for(j=i-1;j>=0;j--)
    {
        cout<<num3[j];
    }

    cout<<endl;


}

关于数组输出的问题,csdn网友帮助我讲解了,我也明白了,引用网友原话是这样的:

系统给char重载了,只有char具有这样的功能,所以只有输出char型数组的时候可以直接输出数组名,其他情况像int型数组就不行,输出数组名显示是数组的首地址!这点要注意啦!

原文地址:https://www.cnblogs.com/jackhub/p/3147256.html