c语言字母可以加减吗,C语言算式加减法运算



/*

通过键盘输入100以内的正整数的加、减法

运算式,请编写一个程序输出运算结果字符串。

输入字符串的格式为:“操作数1 运算符 操作数2”

,“操作数“与”运算符”之间以一个空格隔开。

补充说明:

1.操作数为正整数,不需要考虑结果溢出的情况。

2.若输入算式格式错误,输出结果为“0”。

*/

/*

思路:

1.先判断该运算式合法没有;

2.在把字符型的字符串转化成整形

3.整形做加减运算

*/

#include

#include

#include

//字符串转化成整形方法

int strToint(char *str)

{

int num = 0, len = 0, i = 0, j = 0;

len = strlen(str);

if(len == 0)

{

return NULL;

}else{

for(j = len, i = 0; j >= 1; j--,i++)

{

num += (*(str+i) - 48) * (int)(pow(10,j - 1));

}

}

return num;

}

void arithmetic(const char *pInputStr,long IInputLen,char *pOutputStr)

{

bool b = false;

char ch[3][4];

char c1 = '\0', c2 = '\0';

int i= 0,j = 0, f = 0, s = 0;

int num = 0, num1 = 0,num2 = 0;

//判断格式是否正确

for(i = 0; i < IInputLen; i++)

{

c1 = *(pInputStr + i);

c2 = *(pInputStr + i + 1);

if((c1 == '+' || c1 == '-') && (c2 == '+' || c2 == '-'))

{

b = true;

break;

}

}

if(b)//格式不正确输出0

{

printf("%d\n",num);

return;

}

//把运算数和运算符号分解出来

for(j = 0; j < IInputLen; j++)

{

if(*(pInputStr + j) != ' '){

ch[f][s++] = *(pInputStr + j);

}else{

ch[f][s] = '\0';

f++;

s = 0;

}

}

ch[f][s] = '\0';

//

int num1Len = strlen(ch[0]);

int num2Len = strlen(ch[2]);

//字符型转化成整形

num1 = strToint(ch[0]);

num2 = strToint(ch[2]);

//运算

if(ch[1][0] == '+')

{

num = num1 + num2;

}else if(ch[1][0] == '-'){

num = num1 - num2;

}

printf("%d\n",num);

}

void main()

{

char *p = NULL;

arithmetic("11 + 10",7,p);

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值