首页 > 试题广场 >

通过键盘输入100以内正整数的加、减运算式,请编写一个程序输

[问答题]
通过键盘输入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” 注:格式错误
#我自己测试了几个对着呢,不足之处还望大家指教
while True:
    try:
        list_in = input().split()
        if len(list_in) != 3:
            print('0')
        elif list_in[1] == '+' and (list_in[0])>'0' and list_in[2]>'0':
            result = int(list_in[0]) + int(list_in[2])
            print(str(result))          
        elif list_in[1] == '-' and list_in[0]>'0' and list_in[2]>'0':
            result = int(list_in[0]) - int(list_in[2])
            print(str(result))
        else:      
             print('0')
    except:
        break


发表于 2020-04-18 16:15:04 回复(0)
#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') //获得操作数2    
    {    
        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;    
}    
 

发表于 2014-11-15 16:41:01 回复(0)