依次搜查就行了 要注意m,k,M这几个不是标准单位 要进行换算一下,写着有点麻烦,多注意一些。
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include<string.h> 4 char c[1001]; 5 float swit(char f,int j) 6 { 7 float s = 0,x; 8 int y,i; 9 i = j; 10 while(c[j]>='0'&&c[j]<='9'&&j<strlen(c)) 11 { 12 j++; 13 } 14 x = 1; 15 y = j; 16 y--; 17 while(y>=i) 18 { 19 s += (c[y]-48)*x; 20 x *= 10; 21 y--; 22 } 23 x = 1.0/10; 24 if(c[j] == '.') 25 { 26 j++; 27 while(c[j]>='0'&&c[j]<='9'&&j<strlen(c)) 28 { 29 s += (c[j]-48)*x; 30 x = x/10; 31 j++; 32 } 33 } 34 if(j!=strlen(c)) 35 { 36 if(c[j] == 'm') 37 s = s/1000; 38 if(c[j] == 'k' ) 39 s = s*1000; 40 if(c[j] == 'M') 41 s = s*1000000; 42 } 43 return s; 44 } 45 int main() 46 { 47 int t, i, j, k,count,flag,a[300],g = 0; 48 float s,x,I,v,P; 49 scanf("%d%*c", &t); 50 while(t--) 51 { 52 g++; 53 a['U'] = 1; 54 a['I'] = 1; 55 a['P'] = 1; 56 flag = 0; 57 count = 0; 58 gets(c); 59 k = strlen(c); 60 for(i = 0 ; i < k ; i++) 61 { 62 if(i<k-2&&(c[i] == 'U'||c[i] == 'P'||c[i] == 'I')&&c[i+1] == '=') 63 { 64 j = i+2; 65 s = swit(c[i],j); 66 67 if(c[i] == 'U') 68 { 69 v = s; 70 count++; 71 a[c[i]] = 0; 72 } 73 if(c[i] == 'I') 74 { 75 I = s; 76 count++; 77 a[c[i]] = 0; 78 } 79 if(c[i] == 'P') 80 { 81 P = s; 82 count++; 83 flag = 1; 84 a[c[i]] = 0; 85 } 86 if(count == 2) 87 { 88 break; 89 } 90 i+=2; 91 } 92 } 93 printf("Problem #%d\n",g); 94 if(flag == 0) 95 { 96 printf("P=%.2fW\n",I*v); 97 } 98 else 99 { 100 if(a['U'] == 0) 101 printf("I=%.2fA\n",P/v); 102 else 103 printf("U=%.2fV\n",P/I); 104 } 105 puts(""); 106 } 107 return 0; 108 }