2213: Physics Exam
Description高中物理老师总认为给学生文本形式的问题比给纯计算形式的问题要求更高。毕竟,学生首先得阅读和理解问题。
因此,他们描述一个问题不像”U=10V,I=5A,P=?”,而是”有一个含有U=10V 的电池组和灯泡的电路。现在有I=5A 的电流通过灯泡,问灯泡产生的功率是多少?”
然而,大多数学生并不在乎题目文本。他们只是从文本中提取出:U=10V,I=5A。然后他们想:”我知道哪个公式呢?哦,对了,P=UI。因此P=10V5A=50W。搞定。”
现在,我们只考虑一个P-U-I 类型的问题。即功率,电压和电流中的两个告诉你,你要求剩下那个。
你的任务是写一个程序,从输入文件中读入一些文本问题,然后要你计算剩下那个的值。
Input
第一行为一个正整数,表示数据组数。
每组数据包含一行,为一个包含两个数据区和一些任意单词的字符串。一个数据区具有如下形式:I=xA,U=xV 或P=xW,x 是一个实数。在A,V,W 之前有可能出现前缀m(毫, 千分之一),k(千),M(兆,百万)。以下是几点关于输入的说明:
-
等号(‘=’)只会在数据区出现,不会在其他地方出现;
-
数据区内没有空格字符;
-
P 和U,P 和I,或U 和I 中的一个会给出;
文本问题长度不超过255,且数据组数不超过3 组。
Output
对于每组数据输出一行,形式如:P=xW,I=xA 或U=xV(取决于输入数据),x 为一个实数,保留两位小数。在A,V,W 前不要出现前缀。
Sample Input
Sample Output3
If the voltage is U=200V and the current is I=4.5A, which power is generated?
A light-bulb yields P=100W and the voltage is U=220V. Compute the current, please.
bla bla bla lightning strike I=2A bla bla bla P=2.5MW bla bla voltage?
HintP=900.00W
I=0.45A
U=1250000.00V
利用scanf直接读入浮点数,=作为读入字符数组的终点。
#include<stdio.h>
#include<string.h>
int n;//数据组数n
char ch;
char a[1000];
char firstE;//第一个等号前的字母
char secondE;//第二个等号前的字母
double firstI;//第一个数字
double secondI;//第二个数字
int main()
{
scanf("%d", &n);
while (n--)
{
int length = 0;
while ((ch = getchar()) && ch != '=')
{
a[length++] = ch;
}
firstE = a[--length];
scanf("%lf", &firstI);
ch = getchar();
if (ch == 'm')
{
firstI=firstI/1000;
}
else if (ch == 'k')
{
firstI = firstI * 1000;
}
else if (ch == 'M')
{
firstI = firstI * 1e6;
}
//重复操作
length = 0;
while ((ch = getchar()) && ch != '=')
{
a[length++] = ch;
}
secondE = a[--length];
scanf("%lf", &secondI);
ch = getchar();
if (ch == 'm')
{
secondI = secondI / 1000;
}
else if (ch == 'k')
{
secondI = secondI * 1000;
}
else if (ch == 'M')
{
secondI = secondI * 1e6;
}
//开始判断
if (firstE == 'I'&&secondE == 'U')
{
printf("P=%.2lfW\n", firstI*secondI);
}
else if (firstE == 'I'&&secondE == 'P')
{
printf("U=%.2lfV\n", secondI/firstI);
}
else if (firstE == 'U'&&secondE == 'P')
{
printf("I=%.2lfA\n", secondI/ firstI);
}
else if (firstE == 'U'&&secondE == 'I')
{
printf("P=%.2lfW\n", firstI*secondI);
}
else if (firstE == 'P'&&secondE == 'U')
{
printf("I=%.2lfA\n", firstI / secondI);
}
else if (firstE == 'P'&&secondE == 'I')
{
printf("U=%.2lfV\n", firstI/ secondI);
}
}
return 0;
}