使用32个元素的数组代表unsigned int型数字(32 bit)的加法。
1 #include <stdbool.h> 2 #include <stdio.h> 3 4 unsigned int num1[32]; 5 unsigned int num2[32]; 6 unsigned int sum[33]; 7 8 void init(unsigned int a, unsigned int *arr) { 9 for (int i = 0; i < 32; ++i) { 10 arr[31 - i] = (a & 1); 11 a = a >> 1; 12 } 13 } 14 15 void add() { 16 int s = 0; 17 int c = 0; 18 for (int i = 0; i < 32; ++i) { 19 s = num1[31 - i] + num2[31 - i] + c; 20 c = s / 2; 21 sum[32 - i] = s % 2; 22 sum[31 - i] = c; // 数的位次(31-i)和和的进位位次(31-i)相同 23 } 24 } 25 26 _Bool is_overflow() { return sum[0] == 1; } 27 28 void print_num(unsigned int *arr) { 29 printf(" "); 30 for (int i = 0; i < 32; ++i) { 31 printf("%u", arr[i]); 32 if ((i + 1) % 8 == 0) { 33 printf(" "); 34 } 35 } 36 printf(".\n"); 37 } 38 39 void print_sum(unsigned int *arr) { 40 for (int i = 0; i < 33; ++i) { 41 printf("%u", arr[i]); 42 if (i > 0 && (i % 8 == 0)) { 43 printf(" "); 44 } 45 } 46 printf(".\n"); 47 } 48 49 int main() { 50 unsigned int a; 51 unsigned int b; 52 scanf("%u %u", &a, &b); 53 init(a, num1); 54 init(b, num2); 55 print_num(num1); 56 print_num(num2); 57 58 add(); 59 print_sum(sum); 60 61 if (is_overflow()) { 62 printf("error: overflow\n"); 63 } else { 64 printf("no overflow\n"); 65 } 66 return 0; 67 }
标签:int,32,sum,加法,unsigned,整数,printf,31 From: https://www.cnblogs.com/weixicai/p/17569761.html