輔導(dǎo)孩子C++編程狡恬,實現(xiàn)大數(shù)的加法珠叔,思路比較直接,就是模擬手工運算弟劲,逐位運算祷安,如果有進位則上一位加一。先程序?qū)崿F(xiàn)的減法兔乞,程序的結(jié)構(gòu)大部分是從減法部分拷貝過來的汇鞭。為了簡化處理凉唐,輸入認為是長度小于100的數(shù)字,沒有進行合法性判斷霍骄。也沒有輸入輸出說明台囱。
//大數(shù)的加法
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char First[100],Second[100];
cin>>First>>Second;
int FirstLen=strlen(First),SecondLen=strlen(Second);
//將輸入的數(shù)據(jù)放到整數(shù)數(shù)組中,便于計算读整,結(jié)果保存在數(shù)組c中
int intFirst[100],intSecond[100],c[100];
//首先初始化簿训,避免非正常結(jié)果
for(int i=0;i<100;i++){
intFirst[i]=0;
intSecond[i]=0;
c[i]=0;
}
//輸入的順序是高位在后,低位在前米间,因此需要顛倒一下
//這里的關(guān)鍵是顛倒后數(shù)組下標(biāo)之間的對應(yīng)關(guān)系
for(int i=FirstLen-1;i>=0;i--){
intFirst[FirstLen-1-i]=First[i]-48;
}
for(int i=SecondLen-1;i>=0;i--){
intSecond[SecondLen-1-i]=Second[i]-48;
}
int len=FirstLen;
if(SecondLen>FirstLen)
len=SecondLen;
//這里可以進行加法法運算了强品,問題轉(zhuǎn)換為intFirst與intSecond之間的運算
for(int i=0;i<len+1;i++)
{
c[i]=intFirst[i]+intSecond[i]; //按位進行運算
if(c[i]>=10)
{
//如果結(jié)果小于0,那么從上一位借1當(dāng)10屈糊,結(jié)果需要加上10的榛,上一位減去1
c[i]=c[i]-10;
intFirst[i+1]=intFirst[i+1]+1;
}
}
//下面的代碼是輸出
bool isZero=true;
for(int i=FirstLen;i>=0;i--)
{
//如果高位是0,就不輸出 ,需要注意逻锐,如果結(jié)果是0 困曙,應(yīng)該輸出
if(c[i]==0&&isZero&&i>0)
{
continue;
}
cout<<c[i];
isZero=false;
}
}