Tag:c calculator
#include <stdio.h> #include <stdlib.h>int _add (int a, int b) { return a + b;} Int _sub (int a, int b) { return a - b;} Int _mul (int a, int b) { return a*b;} Int _div (int a, int b) { if (b == 0) &NBSP;&NBSP;{PRINTF ("except digital 0\n"); } return a / b;} Void menu () {printf ("*************************\n");p rintf ("**** 1.add 2.sub ****\n ");p rintf (" **** 3.mul 4.div ****\n ");p rintf (" ******** 0.exit *********\n ");p rintf (" *************************\n ");} Int main () {&NBSP;&NBSP;&NBSP;&NBSP;INT&NBSP;INPUT&NBSP;=&NBSP;1;&NBSP;&NBSP;&NBSP;&NBSP;INT&NBSP;NUM1 = 0; int num2 = 0; int ret = 0; while (input) {menu ();p rintf ("Please select";: "); scanf ("%d ", &input);p rintf (" Please enter two integer operands;: "); scanf ("%d% D ", &num1, &num2);switch (input) {case 1:ret = _add (num1, num2); Break;case 2:ret = _sub (num1, num2);break;case 3: ret = _mul (num1, num2); Break;case 4:ret = _div (NUM1,&NBSP;NUM2); Break;case 0:exit (exit_failure); break;default:printf ("Select Error, please re-select. \ n"); printf ("ret = %d\n", ret); }return 0;} Alternatively, the enumeration structure (enum) can also be implemented: #include <stdio.h> #include <stdlib.h>enum op{exit,add,sub,mul, Div};int _add (int a, int b) { return a + b;} Int _sub (int a, int b) { return a - b;} Int _mul (int a, int b) { return a*b;} Int _div (int a, int b) { if (b == 0) &NBSP;&NBSP;{PRINTF ("except digital 0\n"); } return a / b;} Void menu () {printf ("*************************\n");p rintf ("**** 1.add 2.sub ****\n ");p rintf (" **** 3.mul 4.div ****\n ");p rintf (" ******** 0.exit *********\n ");p rintf (" *************************\n ");} Int (*pfun[5]) (Int, int) = {0, _add, _sub, _mul, _div};int main () { int input = 1; int num1 = 0; int num2 = 0; int ret = 0; while (Input) {menu ();p rintf ("Please choose;:");scanf ("%d", &input);p rintf ("Please enter two integer operands;:"); scanf ("%d%d", &num1, &num2);if ( INPUT&NBSP;>=&NBSP;1&NBSP;&&&NBSP;INPUT&NBSP;<=&NBSP;4) {Ret = pfun[input] (num1, NUM2);} else if (input == 0) {exit (exit_failure);} else{printf ("Select Error \ n");} printf ("ret = %d\n", ret);} return 0;}
This article from "vs LV" blog, declined reprint!
"C Language" analog calculator