c语言编译正整数的运算,华为2014年机试题【100以内正整数的加、减运算】-【C语言/C++】...

一、灵感来源

2013-09-17 | 题目来源 http://blog.csdn.net/net_assassin/article/details/11660869

2013-09-17 | 答案来源 http://blog.csdn.net/net_assassin/article/details/11660869

二、题目

华为2014年机试题2:

通过键盘输入100以内正整数的加、减运算式,请编写一个程序输出运算结果字符串。

输入字符串的格式为:“操作数1 运算符 操作数2”,“操作数”与“运算符”之间以一个空格隔开。

补充说明:

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

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

要求实现函数:

void arithmetic(const char *pInputStr, long lInputLen, char *pOutputStr);

【输入】 pInputStr:  输入字符串

lInputLen:  输入字符串长度

【输出】 pOutputStr: 输出字符串,空间已经开辟好,与输入字符串等长;

【注意】只需要完成该函数功能算法,中间不需要有任何IO的输入输出

示例

输入:“4 + 7”  输出:“11”

输入:“4 - 7”  输出:“-3”

输入:“9 ++ 7”  输出:“0” 注:格式错误

三、C/C++实现

#include

using namespace std;

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

{

const char *input = pInputStr;

char *output = pOutputStr;

int sum = 0;

int operator1 = 0;

int operator2 = 0;

char *temp = new char[5];

char *ope = temp;

while(*input != ' ') //获得操作数1

{

sum = sum*10 + (*input++ - '0');

}

input++;

operator1 = sum;

sum = 0;

while(*input != ' ')

{

*temp++ = *input++;

}

input++;

*temp = '\0';

if (strlen(ope) > 1 )

{

*output++ = '0';

*output = '\0';

return;

}

while(*input != '\0') //获得操作数1

{

sum = sum*10 + (*input++ - '0');

}

operator2 = sum;

sum = 0;

switch (*ope)

{

case '+':itoa(operator1+operator2,pOutputStr,10);

break;

case '-':itoa(operator1-operator2,pOutputStr,10);

break;

default:

*output++ = '0';

*output = '\0';

return;

}

}

int main()

{

char input[] = "4 - 7";

char output[] = " ";

arithmetic(input,strlen(input),output);

cout<

return 0;

}

四、备用

原博主 : http://blog.csdn.net/net_assassin/article/details/11660869

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值