c语言sum函数实现加法,加法运算(c++ 实现)

实现两个数的加法操作,不考虑 负数的情况 #include #include #include using namespace std; string

实现两个数的加法操作,不考虑 负数的情况

#include

#include

#include

using namespace std;

string NumAdd(const string &n1, const string &n2)

{

int len1 = n1.length();

int len2 = n2.length();

std::string num = "0123456789";

int f = 0;

int k = 0;

int i, j;

std::string sum = "";

for (i = len1 - 1, j = len2 - 1; i >= 0 && j >= 0; i--, j--)

{

int s = (n1[i] - '0') + (n2[j] - '0') + f;

f = s / 10;

k = s % 10;

sum += num[k];

}

for (; i >= 0; i--) {

int s = (n1[i] - '0') + f;

f = s / 10;

k = s % 10;

sum += num[k];

}

for(; j >=0; j--) {

int s = (n2[j] - '0') + f;

f = s / 10;

k = s % 10;

sum += num[k];

}

if (f > 0) {

sum += num[f];

}

std::reverse(sum.begin(), sum.end());

return sum;

}

int main(int argc, char *argv[])

{

std::string n1 = "6234456711111111111112341234";

std::string n2 = "5678245111111111111111111111";

std::string sum = NumAdd(n1, n2);

cout << n1 << " + " << n2 << " = " << sum << endl;

return 0;

}

输出结果:

6234456711111111111112341234 + 5678245111111111111111111111 = 11912701822222222222223452345