[C語言] 大數加法

今天心血來潮回去看以前沒看完的Array,大數運算在暫存器有限的電腦是很重要的,而且也能練習對陣列的熟悉度

有了些心得後開始試著寫大數加法,寫了一整個晚上,終於弄出來了~~

雖然程式碼很難看,至少還能正確運算XD

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
void plus(char first[], char second[]);
 
int main(void)
{
 
    char input[600], first[600], second[600], operat[5];
    char* token;
 
    while (fgets(input, 599, stdin) != NULL)
    {
        // Split string into numbers and operator
        token = strtok(input, " ");
        strcpy(first, token);
        token = strtok(NULL, " ");
        strcpy(operat, token);
        token = strtok(NULL, "\n");
        strcpy(second, token);
 
        // Check operator
        if (operat[0] == '+')
        {
            plus(first, second);
            printf("%s\n", first);
        }
        else
        {
            printf("Unknown operator.\n");
        }
    }
 
    return 0;
}
 
void plus(char first[], char second[])
{
    int first_len = strlen(first);
    int second_len = strlen(second);
    int tobe_added = 0, length1, length2, buffer1, buffer2;
    char one[600], two[600];
 
    if (first_len > second_len)
    {
        length1 = first_len;
        length2 = second_len;
        strcpy(one, first);
        strcpy(two, second);
    }
    else
    {
        length1 = second_len;
        length2 = first_len;
        strcpy(one, second);
        strcpy(two, first);
    }
 
    for (int i = 1; i <= length1; i++)
    {
        if (length2 >= i)
        {
            buffer1 = one[length1 - i] - '0';
            buffer2 = two[length2 - i] - '0';
            buffer1 = buffer1 + buffer2 + tobe_added;
        }
        else
        {
            buffer1 = one[length1 - i] - '0';
            buffer1 = buffer1 + tobe_added;
        }
 
        one[length1 - i] = buffer1 % 10 + '0';
        tobe_added = buffer1 / 10;
 
    }
 
    if (tobe_added != 0)
    {
        char temp[] = {(tobe_added + '0'), '\0'};
        strcpy(first, temp);
        strcat(first, one);
    }
    else
    {
        strcpy(first, one);
    }
 
}

留言

取消回覆

粗體斜體刪除線連結引用圖片程式碼

注意:您的電子信箱將不會被公開,且網站連結不會被搜尋引擎採計