字符串的加减法运算1.o

字符串的加减法运算,没有考虑括号,代码如下:

思路:

1:首先去掉输入字符串的非法空格 delAllSpace()

2:判断字符是不是数字 isNum(char)

3:  获得数据 getNum(char *str,int *pindex)

4: 分析表达式,计算结果 fenxi(char *str) 

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>

/* 删除全部空格 */
void delAllSpace(char *str, char ch)
{
	char *pstr = str;
	while (*pstr != '\0')
	{
		*pstr = *str;
		if (*pstr != ' ')
		{
			pstr++;
		}
		str++;
	}
	
}

//判断是不是数字
int isNum(char ch)
{
	int is = 0;
	if (ch >= '0' && ch <= '9')
		is = 1;

	return is;

}

/* 获得数据*/
double getNum(char *str, int *pindex)
{
	double value = 0.0;
	int index = *pindex;
	/* isNum() 取出每个字符 相当于str[i] */
	while (isNum(*(str + index)))
	{
		value *= 10;
		value += *(str+index) - '0';
		index++;
	}
	/* 如果有小数点 */
	if (*(str+index) == '.')
	{
		index++;

		double xiaoshu = 1.0;
		while (isNum(*(str + index)))
		{			
			xiaoshu /= 10;
			value += xiaoshu*(*(str + index) - '0');
			index++;
		}	

	}
	*pindex = index; //记录下指针移动的位置
	return value;
}

double fenxi(char *str)
{
	double value = 0.0;
	int index = 0;
	value = getNum(str, &index);	/* 获取第一个数据 */
	while (1)
	{
		//这时str指针向了一个非数字的字符
		char ch = *(str + index);
		index++;	//这时需要把指针向前移动
		switch (ch)
		{
		case '\0':
			return value;
			break;
		case '+':
			value += getNum(str, &index);
			break;
		case '-':
			value -= getNum(str, &index);
			break;
		default:
			break;
		}
		
	}
}

void main()
{
	char str[1024] = { 0 };	
	//scanf("%s", str);
	scanf("%[^\n]", str); //可以接受空格
	printf("%s\n", str);
	delAllSpace(str, ' ');
	printf("%s\n", str);
	int index = 0;
	//double  value = getNum(str, &index);
	/*printf("获取第一个数据:%.2f\n", value);*/
	
	double value = fenxi(str);
	printf("计算的合是:%.2f\n", value);
	system("pause");
}


  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值