C++高精度减法

该代码段展示了一个C++程序,用于比较两个字符串并根据特定规则进行调整。它首先定义了一个比较函数cmp,然后在main函数中,根据字符串长度和cmp函数的结果交换字符串。之后,将较短的字符串填充0以使两者长度相等,接着逐字符比较,计算差异并存储在数组c中。最后,输出数组c的内容,表示字符串的相对位置差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码如下:

#include <bits/stdc++.h>
using namespace std;
int c[205];
int cmp(string s1, string s2)
{
   int len=s1.size();
   for(int i=0;i<len;i++){
   	if(s1[i]<s2[i]) return -1;
   }
   return 0;
}
int main() {
	string s1, s2;
	cin>>s1>>s2;
	int len1 = s1.size();
	int len2 = s2.size();  
	if (len1 < len2||len1==len2&&cmp(s1,s2)<0){
	swap(s1, s2); swap(len1,len2);
      cout<<'-';	
	} 
	for (int i = 1; i <= len1 - len2; i++) {
		s2 = '0' + s2;
	}
	for (int i = len1 - 1; i >=0; i--) {  
	 if(s1[i]<s2[i])        
	 {                      
	  c[i]+=10;
	  c[i-1]+=-1;
	 }
	 c[i]+=s1[i]-s2[i];
	}
	int f = 0;
	while (c[f] == 0) {
		f++;
	}
	for (int i = f; i < len1; i++) {
		cout << c[i];
	}
	return 0;
}

### C++ 实现高精度减法 为了实现高精度计算,在标准库之外通常会借助第三方库如 GMP (GNU Multiple Precision Arithmetic Library),该库提供了任意精度算术的支持。对于简单的应用场合,也可以通过字符串处理的方式来完成大数运算。 下面是一个基于字符串操作来执行两个整数间高精度减法的例子: ```cpp #include <iostream> #include <string> #include <algorithm> std::string highPrecisionSubtract(const std::string& num1, const std::string& num2) { int borrow = 0; bool isNegativeResult = false; // Ensure num1 >= num2 by swapping if necessary. if (num1.length() < num2.length()) { return "-" + highPrecisionSubtract(num2, num1); } else if (num1.length() == num2.length() && num1 < num2) { isNegativeResult = true; // Mark result as negative when swapping numbers with equal length but smaller value first number. return "-" + highPrecisionSubtract(num2, num1); } size_t maxLength = std::max(num1.size(), num2.size()); std::string n1 = std::string(maxLength - num1.size(), '0') + num1; std::string n2 = std::string(maxLength - num2.size(), '0') + num2; std::string result; for (int i = static_cast<int>(maxLength)-1 ; i>=0 ; --i){ int diff = ((n1[i]-'0')-(n2[i]-'0'))-borrow; if(diff<0){ diff += 10; borrow=1; } else{ borrow=0; } result.push_back('0'+diff); } while (!result.empty() && *result.rbegin() == '0') result.pop_back(); if(result.empty()) return "0"; std::reverse(result.begin(), result.end()); return (isNegativeResult ? "-" : "") + result; } void testHighPrecisionSubtraction(){ std::cout << highPrecisionSubtract("987654321", "123") << "\n"; // Output: 987654198 std::cout << highPrecisionSubtract("123", "987654321") << "\n"; // Output: -987654198 } ``` 此代码片段展示了如何利用字符数组表示的大数值来进行逐位相减并处理借位的情况[^1]。当被减数小于减数时,函数自动调整顺序以确保正向减法,并标记最终结果为负号前缀。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值