c語(yǔ)言高精度加法怎么實(shí)現(xiàn)

小億
90
2024-03-22 18:31:49

實(shí)現(xiàn)高精度加法可以通過(guò)將兩個(gè)大整數(shù)分別存儲(chǔ)在數(shù)組中,然后從低位到高位逐位相加,并考慮進(jìn)位的情況來(lái)實(shí)現(xiàn)。以下是一個(gè)簡(jiǎn)單的C語(yǔ)言實(shí)現(xiàn)高精度加法的示例代碼:

#include <stdio.h>
#include <string.h>

#define MAX_LEN 1000

void add(char num1[], char num2[], char result[]) {
    int len1 = strlen(num1);
    int len2 = strlen(num2);
    
    int i = len1 - 1;
    int j = len2 - 1;
    int carry = 0;
    int k = 0;
    
    while (i >= 0 || j >= 0) {
        int sum = carry;
        if (i >= 0) {
            sum += num1[i] - '0';
            i--;
        }
        if (j >= 0) {
            sum += num2[j] - '0';
            j--;
        }
        
        result[k] = (sum % 10) + '0';
        carry = sum / 10;
        k++;
    }
    
    if (carry) {
        result[k] = carry + '0';
        k++;
    }
    
    result[k] = '\0';
    
    // Reverse the result
    int start = 0;
    int end = k - 1;
    while (start < end) {
        char temp = result[start];
        result[start] = result[end];
        result[end] = temp;
        start++;
        end--;
    }
}

int main() {
    char num1[MAX_LEN], num2[MAX_LEN], result[MAX_LEN];
    
    printf("Enter the first number: ");
    scanf("%s", num1);
    
    printf("Enter the second number: ");
    scanf("%s", num2);
    
    add(num1, num2, result);
    
    printf("The sum is: %s\n", result);
    
    return 0;
}

在這個(gè)示例代碼中,我們首先輸入兩個(gè)大整數(shù),然后調(diào)用add函數(shù)進(jìn)行高精度加法運(yùn)算,最后輸出結(jié)果。您可以根據(jù)需要修改數(shù)組長(zhǎng)度和輸入輸出格式。

0