题目思路很简单,就是在一串字符中把数字提取出来转化为浮点型。关键就是字符串转数字的函数。c有自带的atof可以用,但是我用了觉得不方便,因为它只能针对全是数字字符的字符串,遇到字母和空字符会返回0。因此需要把字符串中的数字单独提取到另一个数组中。
于是我自己写了一个函数,只要给出数字第一位的下标就能把整个数字转化为浮点型。其实写起来不难,但是调试了挺久。虽然用自带的atof比自己写函数快,但是自己实现atof的功能对提升自己编程能力是有好处的,麻烦点也无所谓。
代码如下:
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cmath>
using namespace std;
double unit(char *, int);//检查单位
double My_atof(char *, int);//自己写的字符串转浮点数函数,自带的atof不好用
const int MAX = 1024;
char s[MAX];
int main()
{
//freopen("data.txt", "r", stdin);
int cases;
scanf("%d", &cases);
int count = 0;
while (cases--)
{
double P = 0, U = 0, I = 0;
getchar();
fgets(s, sizeof(s), stdin);
printf("Problem #%d\n", ++count);
int len = strlen(s);
int i, j;
for (i = 0; i < len; i++)
if(s[i] == '=')
{
if (s[i - 1] == 'P')
{
for (j = i; j < len; j++)
if(s[j] == 'W')
break;
P = My_atof(s, i + 1) * unit(s, j);
}
if (s[i - 1] == 'U')
{
for (j = i; j < len; j++)
if (s[j] == 'V')
break;
U = My_atof(s, i + 1) * unit(s, j);
}
if (s[i - 1] == 'I')
{
for (j = i; j < len; j++)
if (s[j] == 'A')
break;
I = My_atof(s, i + 1) * unit(s, j);
}
}
if (!P)
printf("P=%.2lfW\n\n", U * I);
if (!U)
printf("U=%.2lfV\n\n", P / I);
if (!I)
printf("I=%.2lfA\n\n", P / U);
memset(s, 0, sizeof(s));//清空数组,防止影响到下一个测试
}
return 0;
}
double unit(char *s, int j)
{
if (s[j - 1] == 'm')
return 0.001;
if (s[j - 1] == 'k')
return 1000;
if (s[j - 1] == 'M')
return 1000000;
return 1;
}
double My_atof(char *s, int spot)//s是要转化的数组,spot是要转化的数字的第一位在字符串中的下标,函数会自动读取到字母字符为止
{
int len = strlen(s);
int i;
double num = 0;
for (i = spot; i < len; i++)
if (s[i] >= '0' && s[i] <= '9');//让i达到第一个不是数字字符的下标
else
break;
i--;//让i退回到数字字符
for (; spot <= i; spot++)
num += (s[spot] - '0') * pow(10, i - spot);
if(s[++i] == '.')//检测是否有小数点
{
for (; i < len; i++)让i达到第一个不是数字字符的下标
if (s[i + 1] >= '0' && s[i + 1] <= '9');
else
break;
int j = 1;
for (; spot < i; spot++)
num += (s[spot + 1] - '0') / pow(10, j++);
}
return num;
}