初等算数

/*
高精度的计算的时候,采用这种方式:
用字符串读入数据,用数组存储数据

Primary Arithmetic
两个数相加的时候需要进位的次数
输入数据有若干组,每组数据包含两个无符号的整数a,b
对于每组数据,输出两个数相加需要进位的次数。按照如下输出格式。
*/
#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
    char a[11],b[11];
    int num,e;
    int c[11]={0},d[11]={0};
void swap(char str[],int c[])
{
    int i,len = strlen(str);
    for(i=0;i<len;i++)
        c[i]=str[len-1-i]-'0';
}

int main()
{
    memset(a,0,sizeof(a));
    memset(b,0,sizeof(b));
    while(cin>>a>>b)
    {
        if(strcmp(a,"0")==0&&strcmp(b,"0")==0)
            break;
        num = 0;
        swap(a,c);
        swap(b,d);
        e=0;
        num=0;
        for(int i=0;i<11;i++)
            if(c[i]+d[i]+e>=10)
            {
                e=1;
                c[i]=(c[i]+d[i])/10;
                num++;
            }
            else
                e=0;
            if(num==0)
                cout<<"No carry operation."<<endl;
            if(num==1)
                cout<<num<<" carry operation"<<endl;
            if(num>1)
                cout<<num<<" carry operations"<<endl;
    }
    return 0;

}


不使用数组,直接进行数的计算

#include<iostream>
using namespace std;
int main()
{
    int n,m,a,b,c,sum;
    while(cin>>n>>m)
    {
        if(n==0&&m==0)
            break;
        sum =0;
        c=0;
        while(n>0||m>0)
        {
            a=n%10;
            b=m%10;
            if(a+b+c>=10)
            {
                sum++;
                c=1;
            }
            else
                c=0;
            n=n/10;
            m=m/10;

        }
        cout<<sum<<endl;
    }
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值