您的位置:首页 > 编程语言 > C语言/C++

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

2013-09-17 17:42 381 查看
雪影工作室版权所有,转载请注明【http://blog.csdn.net/lina791211】


一、灵感来源

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 <iostream>

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<<output<<endl;
return 0;
}



四、备用

         原博主 : http://blog.csdn.net/net_assassin/article/details/11660869
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐