高精度计算篇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型数组就不行,输出数组名显示是数组的首地址!这点要注意啦!

posted @   胡.杰  阅读(207)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
点击右上角即可分享
微信分享提示