今天心血來潮回去看以前沒看完的Array,大數運算在暫存器有限的電腦是很重要的,而且也能練習對陣列的熟悉度
有了些心得後開始試著寫大數加法,寫了一整個晚上,終於弄出來了~~
雖然程式碼很難看,至少還能正確運算XD
#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); } }
留言