这道题不难,写这道题时挺波折的,一个是在写字符串转化成浮点数的算法时分类不当,以后应先将判断条件想好再写,以免思维混乱,代码量多时应该细心,避免笔误
AC代码如下:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
double toD(char* s){
int i, len, flag;
double a, tag;
len = strlen(s);
flag = 1;
a = 0;
for(i = 2; i < len; ++i){
if(flag == 1 && (s[i] >= '0' && s[i] <= '9')){
a = 10 * a + s[i] - '0';
}
if(!(s[i] >= '0' && s[i] <= '9')){
switch(s[i]){
case '.':
flag = 0;
tag = 0.1;
break;
case 'M':
a = a * 1000000;
break;
case 'm':
a = a * 0.001;
break;
case 'k':
a = a * 1000;
break;
default: break;
}
}
if(flag == 0 && (s[i] >= '0' && s[i] <= '9')){
a = a + tag * (s[i] - '0');
tag = tag * 0.1;
}
}
return a;
}
int main(){
int m, i, j;
char st[2][50];
char s1[50];
char ch;
scanf("%d", &m);
j = 1;
while(m--){
i = 0;
memset(st, 0, sizeof(st));
while(scanf("%s%c",s1, &ch) && ch != '\n'){
if(strchr(s1, '=')) strcpy(st[i++], s1);
}
if(st[0][0] == 'P' && st[1][0] == 'U'){
printf("Problem #%d\n", j);
printf("I=%.2lfA\n", toD(st[0]) * 1.0 / toD(st[1]));
printf("\n");
}
if(st[0][0] == 'U' && st[1][0] == 'P'){
printf("Problem #%d\n", j);
printf("I=%.2lfA\n", toD(st[1]) * 1.0 / toD(st[0]));
printf("\n");
}
if(st[0][0] == 'P' && st[1][0] == 'I'){
printf("Problem #%d\n", j);
printf("U=%.2lfV\n", toD(st[0]) * 1.0 / toD(st[1]));
printf("\n");
}
if(st[0][0] == 'I' && st[1][0] == 'P'){
printf("Problem #%d\n", j);
printf("U=%.2lfV\n", toD(st[1]) * 1.0 / toD(st[0]));
printf("\n");
}
if(st[0][0] == 'I' && st[1][0] == 'U'){
printf("Problem #%d\n", j);
printf("P=%.2lfW\n", toD(st[0]) * toD(st[1]));
printf("\n");
}
if(st[0][0] == 'U' && st[1][0] == 'I'){
printf("Problem #%d\n", j);
printf("P=%.2lfW\n", toD(st[0]) * toD(st[1]));
printf("\n");
}
j++;
}
return 0;
}