判断给出的两数字及其和或积是否在int范围内。int最大为0x7fffffff。数组存放数字,在比较。
代码如下:
1 #include<stdio.h> 2 #include<string.h> 3 4 char s[2000], a[2000], b[2000], op[2]; 5 int A[2000], B[2000], S[2000]; 6 7 void judge() 8 { 9 long long a1, b1, s1; 10 sscanf(a, "%lld", &a1); 11 sscanf(b, "%lld", &b1); 12 sscanf(s, "%lld", &s1); 13 if(a1 > 0x7fffffff) 14 printf("first number too big\n"); 15 if(b1 > 0x7fffffff) 16 printf("second number too big\n"); 17 if(s1 > 0x7fffffff) 18 printf("result too big\n"); 19 } 20 21 void mult() 22 { 23 int i, j; 24 memset(A, 0, sizeof(A)); 25 memset(B, 0, sizeof(B)); 26 memset(S, 0, sizeof(S)); 27 int len1=strlen(a); 28 for(i=0; i<len1; i++) 29 A[len1-1-i]=a[i]-'0'; 30 int len2 = strlen(b); 31 for(j=0; j<len2; j++) 32 B[len2-1-j]=b[j]-'0'; 33 for(i=0; i<=len2; i++) 34 { 35 int c=0; 36 for(j=0; j<=len1; j++) 37 { 38 S[i+j]+=B[i]*A[j]+c; 39 c=S[i+j]/10; 40 S[i+j]%=10; 41 } 42 } 43 for(i=2000; i>0; i--) 44 if(S[i]) break; 45 for(j=0; j<=i; j++) 46 s[j]=S[i-j]+'0'; 47 s[i+1]='\0'; 48 judge(); 49 } 50 void sum() 51 { 52 int i, j, k; 53 memset(A, 0, sizeof(A)); 54 memset(B, 0, sizeof(B)); 55 memset(S, 0, sizeof(S)); 56 int len1=strlen(a); 57 for(i=0; i<len1; i++) 58 A[len1-1-i]=a[i]-'0'; 59 int len2=strlen(b); 60 for( j=0; j<len2; j++) 61 B[len2-1-j]=b[j]-'0'; 62 int t; 63 if(len1>len2) t=len1; 64 else t=len2; 65 int c=0; 66 for(k=0; k<=t; k++) 67 { 68 S[k]=A[k]+B[k]+c; 69 c=S[k]/10; 70 S[k]%=10; 71 } 72 for(i=2000; i>0; i--) 73 if(S[i]) break; 74 for(j=0; j<=i; j++) 75 s[j]=S[i-j]+'0'; 76 s[i+1]='\0'; 77 judge(); 78 } 79 80 int main() 81 { 82 memset(a, 0, sizeof(a)); 83 memset(b, 0, sizeof(b)); 84 while(scanf("%s%s%s%*c", a, op, b)==3) 85 { 86 printf("%s %s %s\n",a,op,b); 87 if (op[0] == '+') sum(); 88 else mult(); 89 memset(a, 0, sizeof(a)); 90 memset(b, 0, sizeof(b)); 91 } 92 return 0; 93 }