原文链接:tecdat.cn/?p=29620
Requirement
In this Assignment, you should write a program that allows the user to perform simple arithmetic in binary. Upon starting, the program should tell the user that it is a binary math program, along with brief instructions on how to use the program.
The program should then enter a loop, where it gives a prompt, such as“input>”. Upon receiving input from the user, the program should process it, report the output result (or error), and loop back to the prompt. This should continue until the user gives the keyphrase to exit the program (keyphrase is your choice, good choices are“quit”,“end”,“exit”, etc.). For example:
Input> 101+1100
10001
Input> 111001-1010
101111
复制代码
Analysis
Binary arithmetic,也就是二进制算法,是程序设计的根底。本题须要实现一个可交互的程序,依据用户输出,实现二进制算法,如二进制加法、二进制减法等。
本题难度不大,留神输出的数据类型是 char,须要拆分后转换为 int,以及 keyphrase 要害响应符号的解决逻辑即可。
Tips
上面是解决用户交互局部的实现
int main(int argc, char *argv[]) {
char input[100];
char *keyphrase = “quit”;
char *add = “+”;
char *sub = “-“;
char mul = ““;
char *div = “/”;
while (1) {
printf("input>");
scanf("%s", input);
if (strncmp(input, keyphrase, strlen(keyphrase)) == 0) {return 0;}
if (strstr(input, add) != NULL) {binary_add(input);
}
if (strstr(input, sub) != NULL) {binary_sub(input);
}
if (strstr(input, mul) != NULL) {binary_mul(input);
}
if (strstr(input, div) != NULL) {binary_div(input);
}
}
return 0;
}