A function is written in C language to implement an integer computer. The program accepts three parameters. The first parameter is the operation item, and the last two parameters are the operands.
Function: Use the parameters of the main function to implement an integer computer. The program can accept three parameters. The first parameter "-a" is used to perform addition, and the "-s" option is used to perform subtraction, the "-m" option performs multiplication, and the "-d" option executes division. The next two parameters are operands. Thinking: two of the three parameters do not need to be processed, but can be passed in directly, and the first operand needs to be processed to ensure that the input parameter is "'-', '-S','-m', '-d' "to facilitate computation. The first step is to convert the operator symbol to the preceding one, and then pass the parameter and operand to the function. The procedure is as follows:
/*** 1. using the parameters of the main function to implement an integer computer, the program can accept three parameters. ** the first parameter "-a" option executes addition, and the "-s" option executes subtraction, ** the "-m" option performs multiplication, and the "-d" option performs division. The next two parameters are operands. */# Include <stdio. h> # include <stdlib. h> # include <assert. h> int my_math (char * p, int num1, int num2) {assert (p); if (p = "-a") return num1 + num2; else if (p = "-s") return num1-num2; else if (p = "-m") return num1 * num2; else if (p = "-d") return num1/num2; else return 0 ;}int main () {char a, B; char * p = & B; int num1 = 0; int num2 = 0; printf ("Enter the formula to calculate:"); scanf ("% d % c % d", & num1, &, & num2); // input formula, nu M1 and num2 are the operands. a stores the while (1) operator // respectively assign values to the parameter pointer p, '+ ','-','*','/', corresponds to "-a,-s,-m,-d" respectively. if other symbol teams p are assigned '\ 0' {if (a =' + ') {p = "-a"; break;} else if (a = '-') {p = "-s"; break ;} else if (a = '*') {p = "-m"; break;} else if (a = '/') {p = "-d "; break;} else * p = '\ 0';} int result = my_math (p, num1, num2); // function call. The result is displayed. Printf ("% d % c % d = % d \ n", num1, a, num2, result); // Output system ("pause"); return 0 ;}
After verification, the result is correct. Note: Do not enter the equal sign when entering the arithmetic expression. If you want to calculate the value of 5 plus 3, enter "5 + 3!