大概是没有这么麻烦的,就按你给的例子来吧,假设接收到的数据存储在char dat[10]里面。
只需要dat[0]-='0';即可得到数字形式存储的一串数组。
此时从最低位往高位一路算过去,带上借位,就是普通的数学计算,想算多少位的数据都可以。
比如你给出的109593354(去掉小数点了),假设下一个是110000001。
那么给出一段示例程序:
- #include<math.h>
- #define MAX_DIGITS 9 // 假设最大9位数字(可根据需要调整)
- // 函数:比较两个大数字符串的大小
- // 返回值:1 表示 num1 > num2,-1 表示 num1 < num2,0 表示相等
- int compare_large_numbers(const char* num1, const char* num2) {
- for (int i = 0; i < MAX_DIGITS; i++) {
- if (num1[i] > num2[i]) return 1;
- if (num1[i] < num2[i]) return -1;
- }
- return 0;
- }
-
- // 函数:按位计算差值,并将结果转换为long类型
- long subtract_large_numbers(const char* num1, const char* num2) {
- long result = 0;
- int borrow = 0;
-
- // 从最低位开始逐位相减
- for (int i = MAX_DIGITS - 1; i >= 0; i--) {
- int digit1 = num1[i] - '0'; // 将字符转换为数字
- int digit2 = num2[i] - '0'; // 将字符转换为数字
- int temp_diff = digit1 - digit2 - borrow;
-
- // 处理借位
- if (temp_diff < 0) {
- temp_diff += 10;
- borrow = 1;
- } else {
- borrow = 0;
- }
- // 更新结果
- result = result + temp_diff*pow(10,MAX_DIGITS-1-i);
- }
-
- return result;
- }
-
- // 主函数
- int main()
- {
- // 输入两个数字字符串
- const char num1[MAX_DIGITS + 1] = "109593354";
- const char num2[MAX_DIGITS + 1] = "110000001";
- // 比较两个数的大小
- int cmp = compare_large_numbers(num1, num2);
- long difference;
- if (cmp > 0) {
- // num1 > num2,直接计算 num1 - num2
- difference = subtract_large_numbers(num1, num2);
- } else if (cmp < 0) {
- // num1 < num2,计算 num2 - num1,并取负
- difference = subtract_large_numbers(num2, num1);
- difference = -difference;
- } else {
- // num1 == num2,差值为 0
- difference = 0;
- }
-
- // 输出结果
- printf("diff:%ld",difference);
- return 0;
- }
复制代码
|