?? calc.c
字號:
/* * calc.c - a very small calculator. * * Copyright (C) YRP Ubiquitous Networking Laboratory, 2005. */#include <basic.h>#include <stdio.h>#include <tk/tkernel.h>typedef enum { OP_NOP, OP_PLUS, OP_MINUS, OP_MUL, OP_DIV} CalcOp;/* * A very small calculator. * It accepts only the following formula: * <number1><op><number2> * where * <number1> an arbitrary decimal number * <op> '+', '-', '*' or '/' * <number2> another arbitrary decimal number * Any white spaces can be inserted between two elements. * * input: * input input string which contains a formula (IN) * output output buffer for storing a result (OUT) * return: error code * */EXPORT ER tet_calc(UB *input, UB *output){ ER ercd; if (input == NULL || output == NULL) { return E_PAR; } /* calculation procedure */ { UB *p, *q; INT num1, num2, result; CalcOp op; ercd = E_OK; p = input; /* skip white spaces */ while (*p == ' ') { p++; } /* parse the first digits */ num1 = 0; q = p; while (*q >= '0' && *q <= '9') { num1 = (num1 * 10) + (*q - '0'); q++; } if (p == q) { /* parse error */ ercd = E_OBJ; goto EXIT; } p = q; /* skip white spaces */ while (*p == ' ') { p++; } /* parse an operand. error if other character is found. */ switch (*p++) { case '+': op = OP_PLUS; break; case '-': op = OP_MINUS; break; case '*': op = OP_MUL; break; case '/': op = OP_DIV; break; default: /* parse error */ ercd = E_OBJ; goto EXIT; /*NOTREACHED*/ break; } /* skip white spaces */ while (*p == ' ') { p++; } /* parse the second digits */ num2 = 0; q = p; while (*q >= '0' && *q <= '9') { num2 = (num2 * 10) + (*q - '0'); q++; } if (p == q) { /* parse error */ ercd = E_OBJ; goto EXIT; } p = q; /* skip white spaces */ while (*p == ' ') { p++; } /* check if a null character is found */ if (*p != '\0') { /* parse error */ ercd = E_OBJ; goto EXIT; } if (ercd == E_OK) { /* calculate the parsed formula */ result = 0; switch (op) { case OP_PLUS: result = num1 + num2; break; case OP_MINUS: result = num1 - num2; break; case OP_MUL: result = num1 * num2; break; case OP_DIV: result = num1 / num2; break; default: ercd = E_OBJ; goto EXIT; /*NOTREACHED*/ break; } } /* set the result to output buffer */ sprintf(output, "%d\n", result); }EXIT: return ercd;}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -