#include \n#include \n#include \n\nstd::string subtract(const std::string& num1, const std::string& num2) {\n std::string result;\n \n int len1 = num1.size();\n int len2 = num2.size();\n int carry = 0;\n \n for (int i = len1 - 1, j = len2 - 1; i >= 0 || j >= 0 || carry != 0; i--, j--) {\n int digit1 = (i >= 0) ? num1[i] - '0' : 0;\n int digit2 = (j >= 0) ? num2[j] - '0' : 0;\n \n int diff = digit1 - digit2 - carry;\n if (diff < 0) {\n diff += 10;\n carry = 1;\n } else {\n carry = 0;\n }\n \n result.push_back(diff + '0');\n }\n \n std::reverse(result.begin(), result.end());\n \n return result;\n}\n\nint main() {\n std::string num1 = "12345678901234567890";\n std::string num2 = "98765432109876543210";\n \n std::string result = subtract(num1, num2);\n \n std::cout << result << std::endl;\n \n return 0;\n}\n\n本示例中,subtract 函数使用两个字符串参数 num1num2,并返回它们的差值。代码从字符串末尾开始遍历,并进行减法运算。carry 变量用于记录借位。每次减法运算后,结果的每一位数字将转换为字符并添加到结果字符串中。最后,结果字符串被反转并返回。在 main 函数中,将两个高精度数分别作为参数传递给 subtract 函数,并打印结果。\n\n该程序的输出为:-86419753208641975320

C++ 高精度减法算法实现 - 字符串表示

原文地址: https://www.cveoy.top/t/topic/qaD0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录