UVa 537 - Artificial Intelligence?解题报告

题目思路很简单,就是在一串字符中把数字提取出来转化为浮点型。关键就是字符串转数字的函数。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;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值