⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 calc.c

📁 运行于T-Engine(使用T-Kernel操作系统)的实例源码
💻 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 + -