大数加法
void B_add(char *a, char *b, int i, int r) // a = a + b, i为第i位,r为进位 { int d = r; if(i >= strlen(b)) //以b终结为return的标识 { if(r == 0) { if(!(a[i] >= '0' && a[i] <= '9')) a[i] = '\0'; return; } } else d += b[i] - '0'; if(i < strlen(a)) d += a[i] - '0'; a[i] = d % 10 + '0'; // 赋给a时别忘了 + '0' B_add(a, b, i + 1, d / 10); }
循环写法:
void add(char *a, char *b) { int i = 0, r = 0, d; int len1 = strlen(a), len2 = strlen(b); while(i <= len1 || i <= len2) { d = r; if(i < len1) d += a[i] - '0'; if(i < len2) d += b[i] - '0'; a[i] = '0' + d % 10; r = d / 10; i++; } if(d == 0) a[i - 1] = '\0'; else a[i] = '\0'; }
6.2.(3)
#include <stdio.h> #include <string.h> #define maxn 10010 void add(char *str, char *tmp) { int d, r, len1, len2, i; i = r = 0; len1 = strlen(str); len2 = strlen(tmp); while(i < len1 || i < len2) { d = 0; if(i < len1) d += str[i] - '0'; if(i < len2) d += tmp[i] - '0'; d += r; str[i] = '0' + d % 10; r = d / 10; i++; } if(r != 0) str[i] = '0' + r, str[i + 1] = '\0'; else str[i] = '\0'; } void print(char *str) { int i; int len = strlen(str); for(i = len - 1; i >= 0; i--) printf("%c", str[i]); printf("\n"); } int main() { int a, n, cnt, i, r, d; int len1, len2; char str[maxn], tmp[maxn]; str[0] = '0', str[1] = '\0'; scanf("%d%d", &a, &n); cnt = r = 0; while(n--) { tmp[cnt] = '0' + a; tmp[cnt + 1] = '\0'; add(str, tmp); print(str); cnt++; } return 0; }
自己选择的路,跪着也要走完。朋友们,虽然这个世界日益浮躁起来,只要能够为了当时纯粹的梦想和感动坚持努力下去,不管其它人怎么样,我们也能够保持自己的本色走下去。