AOAPC I: Beginning Algorithm Contests (Rujia Liu) :: Volume 1. Elementary Problem Solving :: String
Description
物理老师提问,根据 P = IU 这个公式计算并回答。
提问会告诉你公式中的任意两个元素的值,求出第三个元素的值。
因此,提问语句中含有两个 DataField,DataField的格式如下:
- DataField ::= Concept '=' RealNumber [Prefix] Unit
- Concept ::= 'P' | 'U' | 'I'
- Prefix ::= 'm' | 'k' | 'M'
- Unit ::= 'W' | 'V' | 'A'
其中,Prefix可为 m (milli) 、k (kilo) 或 M (Mega) 。
并且题目的输入保证如下三点:
- “=”在提问语句里,只出现在DataField中。
- DataField中不出现多余空格。
- 题目保证三个元素中有且只有给出两个元素的值。
Type
String
Analysis
找到提问语句中的“=”,以“=”为基准,
在“=”两边找到我们需要的数据即可。
Solution
// UVaOJ 537
// Artificial Intelligence
// by A Code Rabbit
#include <cstdio>
#include <cstring>
#include <iostream>
#include <string>
using namespace std;
const char CONCEPT[] = {'I', 'U', 'P'};
string str;
double real[3];
bool bo[3];
void Read(int idx);
int main() {
int tot_case;
scanf("%d", &tot_case);
getchar();
for (int t = 1; t <= tot_case; t++) {
// Input.
getline(cin, str);
// Solve.
memset(bo, false, sizeof(bo));
Read(str.find_first_of('='));
Read(str.find_last_of('='));
// Output.
printf("Problem #%d\n", t);
if (!bo[0]) printf("I=%.2lfA\n", real[2] / real[1]);
else if (!bo[1]) printf("U=%.2lfV\n", real[2] / real[0]);
else if (!bo[2]) printf("P=%.2lfW\n", real[0] * real[1]);
printf("\n");
}
return 0;
}
void Read(int idx) {
double val; char ch;
string tmp = str.substr(idx + 1);
sscanf(tmp.c_str(), "%lf%c", &val, &ch);
if (ch == 'm') val /= 1000;
else if (ch == 'k') val *= 1000;
else if (ch == 'M') val *= 1000000;
char concept = str[idx - 1];
for (int i = 0; i < 3; i++) {
if (concept == CONCEPT[i]) {
real[i] = val;
bo[i] = true;
}
}
}