c++无限小数加法实现

昨填跟女朋友玩10以内的加减法,1分钟内算不出来罚钱,我肯定果断答应啊,天底下的钱都这么好赚了吗?然而并没有!!!

 

没想到他给我出的是22位小数点25位小数点的数相加,直接蒙逼了~~~,下午刚好做快手笔试,vs打开着,试试long double类型吧,然而long double最多16位小数。怎么办,为了不再让邪恶的女盆友把我的钱包变瘦,我熬着夜变出了一套能对无限位小数进行加的算法。

 

先看劲爆效果图:

c++无限小数加法实现_第1张图片

 

直接上代码

详情见我的github:https://github.com/LixinLu42/plus_subtraction_ifinite_bite_num

欢迎大家关注骚扰我的git,有bug还望各位看官下方留言批评指正。

 

大致思路:

将给的两个数保存为string格式,并已小数点(“.”)为分界拆分整数和小数,循环计算每一位的相加,并把结果保存到vector数组,这样可以避开c++最大位数的限制,从而达到无限位数加法。

 

主要代码:


	string n1 = "5.275764315767345467345711111111111111111111111111111";
	string n2=  "9.64542187673346464573464871111111111111111111111111111111111111111111";
	int pose_n1 = n1.find(".");
	int pose_n2 = n2.find(".");

	string zhengshu_str_n1 = n1.substr(0, pose_n1);
	int zhengshu_int_n1 = atoi(zhengshu_str_n1.c_str());

	string zhengshu_str_n2 = n2.substr(0, pose_n2);
	int zhengshu_int_n2 = atoi(zhengshu_str_n2.c_str());

	int str_n1 = n1.length();
	int str_n2 = n2.length();
	int jinwei = 0;
	vector out;
	if (str_n2 > str_n1) {

		for (int j = 0; j < str_n2 - str_n1; j++) {
			string more1 = n2.substr(str_n2 - j - 1, 1);
			int more = atoi(more1.c_str());
			out.push_back(more);
		}

		for (int i = 0; i < str_n1; i++) {
			string t1 = n1.substr(str_n1-i-1, 1);
			string t2 = n2.substr(str_n1 - i - 1, 1);
			if (t1 == "." || t2 == ".") {
				break;
			}
			else {
				int x1 = atoi(t1.c_str());
				int x2 = stoi(t2.c_str());
				int sum = x1 + x2 + jinwei;
				if (sum > 9) {
					jinwei = 1;
					sum = sum - 10;
					out.push_back(sum);
				}
				else {
					jinwei = 0;
					out.push_back(sum);
				}
			}
		}
	}
	else if (str_n1 > str_n2) {

		for (int j = 0; j < str_n1 - str_n2; j++) {

			string more1 = n1.substr(str_n1 - j - 1, 1);
			int more = atoi(more1.c_str());
			out.push_back(more);
		}


		for (int i = 0; i < str_n2; i++) {
			string t1 = n1.substr(str_n2 - i - 1, 1);
			string t2 = n2.substr(str_n2 - i - 1, 1);
			int x1 = atoi(t1.c_str());
			int x2 = stoi(t2.c_str());
			int sum = x1 + x2 + jinwei;

			if (sum > 9) {
				jinwei = 1;
				sum = sum - 10;
				out.push_back(sum);
			}
			else {
				jinwei = 0;
				out.push_back(sum);
			}
		}
	}
	else{
		for (int i = 0; i < str_n2; i++) {
			string t1 = n1.substr(str_n2 - i - 1, 1);
			string t2 = n2.substr(str_n2 - i - 1, 1);
			int x1 = atoi(t1.c_str());
			int x2 = stoi(t2.c_str());
			int sum = x1 + x2 + jinwei;
			if (sum > 9) {
				jinwei = 1;
				sum = sum - 10;
				out.push_back(sum);
			}
			else {
				jinwei = 0;
				out.push_back(sum);
			}
		}
	}
	cout << zhengshu_int_n1 + zhengshu_int_n2 << ".";
	for (int i = out.size(); i > 0; i--) {
		cout << out[i - 1] ;
	}

结尾撒狗粮   /*—*\,  heiheihei

 

你可能感兴趣的:(vs,C++,git)