C语言的大数相加
两个很大的数相加,可以用两个字符串str1和str2进行操作,参考程序如下:
#include<iostream>
#include<string>
#include<stack>using namespace std;
int main(void)
{
string str1,str2;
stack<int>stack_ex;
int str1_length,str2_length;
int carry = 0;//进位的控制
int tmp;while(cin >> str1 >> str2)
{
str1_length = str1.size();
str2_length = str2.size();int i = str1_length - 1;
int j = str2_length - 1;
for(; i >= 0 && j >= 0; i--,j--)
{
tmp = str1[i] - 0 + str2[j] - 0 + carry;
if(tmp < 10)
{
carry = 0;
stack_ex.push(tmp);
}
else
{
carry = 1;
stack_ex.push(tmp % 10);
}
}if(str1_length >= str2_length)
{
for(; i >= 0; i--)
{
tmp = str1[i] - 0 + carry;
if(tmp < 10)
{
carry = 0;
stack_ex.push(tmp);
}
else
{
carry = 1;
stack_ex.push(tmp % 10);
}
}
}
else
{
for(; j >= 0; j--)
{
tmp = str2[j] - 0 +carry;
if(tmp < 10)
{
carry = 0;
stack_ex.push(tmp);
}
else
{
carry = 1;
stack_ex.push(tmp % 10);
}
}
}
while(!stack_ex.empty())
{
cout<< stack_ex.top();
stack_ex.pop();
}
cout<<endl;
}
return 0;
}
补充:软件开发 , C语言 ,