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

这是一个C++程序,用于接收100以内正整数的加、减运算式作为输入,然后输出运算结果。程序首先检查输入字符串的格式,如果格式正确则进行计算,否则输出“0”。示例包括了加法、减法和格式错误的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
三、题目描述(50分): 
通过键盘输入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” 注:格式错误
*/

#include <iostream>
#include <string>
using namespace std;

#define N 10

void arithmetic(const char *pInputStr, long lInputLen, char *pOutputStr)
{
	char *pInput = const_cast<char *>(pInputStr);
	char ch;
	int index1 = 0;
	int index2 = 0;
	int index3 = 0;	
	char op1[N];
	char op[N];
	char op2[N];
	
	//判断输入内容是否为数字,空格及运算符.
	int cnt = 0;
	for(int i = 0; i < lInputLen; i++)
	{	
		ch = pInput[i];
		if(!isdigit(ch) && ch != ' ' && ch != '+' && ch != '-')
			return;
	}
	
	for(int j = 0; j < lInputLen; j++)
	{
		ch = pInput[j];
		if(ch == ' ')
		{
			cnt++;
			if(cnt > 2)
			{
				cout << "too much space.";
				return;
			}
			continue;
		}
		
		if(cnt == 0)		//操作数op1.
			op1[index1++] = ch;//strcat(op1,ch);
		else if(cnt == 1)	//操作符.
		{
			//或者if(pInput.rfind(' ') - pInput.find(' ') != 1)return;//格式错误.
			op[index2++] = pInput[j];
			if(index2 > 1)//判断类似++的情况.
			{
				cout << "格式错误!";
				return;
			}
		}
		else if(cnt == 2)	//操作数op2.
		{
			op2[index3++] = pInput[j];
		}
	}
	op1[index1] = op[index2] = op2[index3] = '\0';
	
	cout << "op1:" << op1 << endl;
	cout << "op:" << op << endl;
	cout << "op2:" << op2 << endl;
	
	int iop1 = atoi(op1);
	int iop2 = atoi(op2);
	int temp = 0;
	if(op[0] == '+')
		temp = iop1 + iop2;
	else if(op[0] == '-')
		temp = iop1 - iop2;
	cout << temp << endl;
	
	if(temp < 0)
	{
		pOutputStr[0] = '-';
		itoa(-temp,pOutputStr+1,10);
	}
	else
		itoa(temp,pOutputStr,10);
	cout << "pOutputStr:" << pOutputStr << endl;
}

int main()
{
	char *pch1 = "4 + 7";
	int len1 = strlen(pch1);
	char result1[N];
	arithmetic(pch1,len1,result1);	
	
	char *pch2 = "4 - 7";
	int len2 = strlen(pch2);
	char result2[N];
	arithmetic(pch2,len2,result2);	
	
	char *pch3 = "4 ++ 7";
	int len3 = strlen(pch3);
	char result3[N];
	arithmetic(pch3,len3,result3);	
	
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值