高中数学扩展/数学编程/练习 1:处理命令
外观
包含
stdio.h
conio.h
类型定义
TRUE 和 FALSE 的值,用于摆脱标准 C 语法中仅仅测试零/非零的习惯。
函数原型
原型,这样我们就不必担心前向引用。
全局变量
done = main 中的循环控制。
r = 分母(运算符右侧)。
l = 分子(运算符左侧)。
函数定义 init - 设置全局变量。
input_message = 提示输入命令。
input = 读取命令。
get_integer = 读取一个整数。
retrieve_keypress = 查找按键按下。
validate = 确保命令是程序可以处理的。
execute_command = 将命令映射到实现它的例程。
output_divide = 实现除法'/'。
output_modulus = 实现模运算 '%'。
output_values = 打印 l 和 r 的值。
//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++;
break;
}
}
void output_divide()
{
if (l > 0)
{
cprintf("%d / %d = %d.\n",r,l,r/l);
}
else
{
cprintf("r = %d, l = %d. Please set l to a value other than 0.\n",r,l);
}
}
void output_modulus()
{
if (l > 0)
{
cprintf("%d %% %d = %d.\n",r,l,r%l);
}
else
{
cprintf("r = %d, l = %d. Please set l to a value other than 0.\n",r,l);
}
}
void output_values()
{
cprintf("r = %d, l = %d.\n",r,l);
}
void main()
{
char command;
init();
input_message();
while(!done)
{
command=input();
execute_command(command);
}
}