天天看点

华为上机真题_算术运算

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

void arithmetic(char *pInputStr1, long lInputLen, char *pOutputStr) {

    char *pch = NULL;

    char *cur = malloc(lInputLen + 1);

    *pOutputStr = '\0';

    int oprand1 =0, oprand2 = 0, count = 0;

    char *operator = NULL;

    strcpy(cur, pInputStr1);

    pch = strtok(cur, " ");//获取第一个子字符串

    while(pch != NULL) {//继续获取其它子串

        if (count == 0) {

            oprand1 = atoi(pch);

        } else if(count == 2) {

            oprand2 = atoi(pch);

        } else {

            operator = pch;

        }

        pch = strtok(NULL, " ");

        count ++;

    }

    if (strcmp(operator, "+") == 0){

            oprand1 += oprand2;

            sprintf(pOutputStr + strlen(pOutputStr), "%d", oprand1);

    }else if (strcmp(operator, "-") == 0){

            oprand1 -= oprand2;

            sprintf(pOutputStr + strlen(pOutputStr), "%d", oprand1);

    }else {

        sprintf(pOutputStr + strlen(pOutputStr), "%d", 0);

        printf("格式错误\n");

    }

    free(cur);

}

int main(void) {

    char pInputStr[128] = {"3 + 5"};

    char pOutputStr[128] = {0};

    arithmetic(pInputStr, strlen(pInputStr), pOutputStr);

    printf("输出:%s\n", pOutputStr);

    return 0;

}