题目大意:输入字符串,其中包含功率,电流,电压其中两项的数值,m,k,M分别表示0.001,1000,1000000倍。求未知的第三项的数值。
解题思路:用atof函数读数值,注意有m,k,M时换算,如果不用atof函数,会麻烦一些,还要注意负数的情况。
ac代码:
#include <iostream>
#include <stdlib.h>
#include <cstring>
#include <map>
using namespace std;
char a[1005], temp[105];
int n, cnt=1, len, t1, t2, t3;
double I, P, U, temp2;
map <char, double>ma;
int main(){
ma['m'] = 0.001, ma['k'] = 1000, ma['M'] = 1000000;
scanf("%d", &n);
getchar();
while (n--){
gets(a);
len = strlen(a);
t1 = t2 = t3 = 0;
for (int i=0; i<len; i++)
if (a[i-1] == '='){
memset(temp, 0, sizeof(temp));
for (int j=0; !isalpha(a[i]); j++,i++)
temp[j] = a[i];
temp2 = atof(temp);
if (a[i] == 'm' || a[i] == 'k' || a[i] == 'M')
temp2 = temp2 * ma[ a[i++] ];
if (a[i] == 'W')
P = temp2, t1 = 1;
else if (a[i] == 'V')
U = temp2, t2 = 1;
else
I = temp2, t3 = 1;
}
printf("Problem #%d\n", cnt++);
if (!t1)
printf("P=%.2lfW\n", U*I);
else if (!t2)
printf("U=%.2lfV\n", P/I);
else
printf("I=%.2lfA\n", P/U);
printf("\n");
}
return 0;
}