High School Mathematics Extensions/Mathematical Programming/Exercise 1: The Complete Program
Appearance
Explanation
[edit | edit source]Program for looking at integer division and modulus.
Code to change
[edit | edit source] Add and replace the following code:
//includes #include <stdio.h> #include <conio.h> //type definitions #define TRUE 1 #define FALSE 0 //function prototypes void init(); void input_message(); char input(); char retrieve_keypress(); char validate(char check_me); void execute_command(char command); void output_divide(); void output_modulus(); void output_values(); int get_integer(); //global variables unsigned char done; int r; int l; //function definitions void init() { done=FALSE; r=5; l=2; } void input_message() { cprintf("Key Action.\n"); cprintf("/ Display r/l = result.\n"); cprintf("%% Display r%%l = result.\n"); cprintf("= Display r=value, l=value.\n"); cprintf("r or R Set the value for r.\n"); cprintf("l or L Set the value for l.\n"); cprintf("x or X End program.\n"); } char input() { char read; read=retrieve_keypress(); while (!validate(read)) { cprintf("\nInvalid Command.\n"); input_message(); read=retrieve_keypress(); } return read; } int get_integer() { int ret_val; char lastpress; cprintf("Enter integer: "); cscanf("%i",&ret_val); lastpress=getch(); cprintf("\n"); return ret_val; } char retrieve_keypress() { char ret_val; ret_val=getche(); cprintf("\n"); return ret_val; } char validate(char check_me) { char ret_val=0; switch (check_me) { case '/': case '%': case '=': case 'r': case 'R': case 'l': case 'L': case 'x': case 'X': ret_val++; break; } return ret_val; } void execute_command(char command) { switch (command) { case '/': output_divide(); break; case '%': output_modulus(); break; case '=': output_values(); break; case 'r': case 'R': r=get_integer(); output_values(); break; case 'l': case 'L': l=get_integer(); output_values(); break; case 'x': case 'X': done=TRUE; break; } } void output_divide() { if (r > 0) { cprintf("%d / %d = %d.\n",l,r,l/r); } else { cprintf("l = %d, r = %d. Please set r to a value other than 0.\n",r,l); } } void output_modulus() { if (r > 0) { cprintf("%d %% %d = %d.\n",l,r,l%r); } else { cprintf("l = %d, r = %d. Please set r to a value other than 0.\n",r,l); } } void output_values() { cprintf("l = %d, r = %d.\n",l,r); } void main() { char command; init(); input_message(); while(done!=TRUE) { command=input(); execute_command(command); } }