High School Mathematics Extensions/Mathematical Programming/The Complete Program
Appearance
Code to copy
[edit | edit source] The following code is valid:
//includes #include <stdio.h> #include <conio.h> //function prototypes void init(); void input_message(); char input(); void execute_command(char); char retrieve_keypress(); char validate(char check_me); double process(); void output(); float get_delta(); //type definitions //global variables char done; double x_val; double delta; //function definitions void init() { done=0; x_val=1.2; delta=0.1; } void input_message() { cprintf("Key Action.\n"); cprintf("= Display f(x) = result.\n"); cprintf("d or D Change delta.\n"); cprintf("+ Add delta to x.\n"); cprintf("- Subtract delta from x.\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; } 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 'd': case 'D': case 'x': case 'X': ret_val++; break; } return ret_val; } void execute_command(char command) { switch (command) { case '=': output(); break; case '+': x_val+=delta; output(); break; case '-': x_val-=delta; output(); break; case 'd': case 'D': delta=get_delta(); break; case 'x': case 'X': done++; break; } } void output() { double f_val; f_val=process(); cprintf("f(%.3f)=%.6f.\n",x_val,f_val); } double process() { return x_val * x_val; } float get_delta() { float f_val; char lastpress; cprintf("Enter delta: "); cscanf("%f",&f_val); lastpress=getch(); cprintf("\n"); if(f_val < 0.001) { f_val=0.001; cprintf("Delta must be floating point number greater than or equalt to 0.001.\nDelta set to %f.\n",f_val); } else { cprintf("Delta set to %f.\n",f_val); } return f_val; } void main() { char command; init(); input_message(); while(!done) { command=input(); execute_command(command); } }