这是一道简单的字符串处理题。由于'='是DataField中才会出现的,故读到'='时则已经读到了等式。用'='前一个字符判断读到的是P,U,I中的哪一个,'='后读入的是一个double型和一个char型,通过读入的char型判断是否有后缀prefix即可。
我的解题代码如下:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
using namespace std;
bool U,I,P;
double d,u,i,p;
char prefix;
char ch,last_ch;
void getdata()
{
while((ch=getchar())!=EOF)
{
if(ch=='=') break;
// printf("%c",ch);
last_ch=ch;
}
scanf("%lf%c",&d,&prefix);
switch(prefix)
{
case 'm': d /= 1000; break;
case 'k': d *= 1000; break;
case 'M': d *= 1000000; break;
}
switch(last_ch)
{
case 'U': U=1; u=d; break;
case 'I': I=1; i=d; break;
case 'P': P=1; p=d; break;
}
}
int main()
{
int T;
scanf("%d\n",&T);
for(int k=1; k<=T; k++)
{
U=I=P=0;
getdata();
getdata();
while((ch=getchar())!=EOF)
if(ch=='\n') break;
printf("Problem #%d\n",k);
if(!U) { u=p/i; printf("U=%.2lfV\n",u); }
else if(!I) { i=p/u; printf("I=%.2lfA\n",i); }
else if(!P) { p=u*i; printf("P=%.2lfW\n",p); }
printf("\n");
}
return 0;
}
其中U,I,P为1 代表他们是已知条件,为0代表是要求的。