字符串的加减法运算,没有考虑括号,代码如下:
思路:
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");
}