天天看點

華為上機真題_算術運算

#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;

}