小项目1 ---C 语言做一个简单的计算器
bk_3d33e46410a73b90105787f79ffae2a7_l6p323.jpg
1,项目说明:
实现一个简易的仅支持两个操作数运算的计算器,不涉及词法分析与语法树,内容很简单,适合 C 语言入门(刚掌握语法程度)的进行练手。
2,项目介绍
能执行加、减、乘、除操作。本程序涉及的所有数学知识都很简单,但输入过程会增加复杂性。因为我们需要检查输入,确保用户没有要求计算机完成不可能的任务。还必须允许用户一次输入一个计算式,例如: 32.4 + 32 或者 9 * 3.2
2.1,项目流程:
1.获取用户输入的计算表达式。
2.检查输入的表达式格式,确保表达式对应的实际操作可以执行。
3.执行计算。
4.返回计算结果并在终端打印。
2.2,项目效果图:
![S6Q]OY{HLV``7YHC41(CZMK.jpg](https://img.haomeiwen.com/i2619158/238b2ea80960b82f.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
3,项目实现
3.1获取输入
double number1=0.0; // 定义第一个操作数
double number2=0.0; // 定义第二个操作数
char operation=0; // operation 必须是 '+' '-' '*' '/' 或 '%'
printf("\nEnter the calculation\n");
scanf("%lf%c%lf",&number1,&operation,&number2);```
##### 3.2输入检查
当输入的操作为 / 或者 % 时,第二个操作数不能为 0 。如果为 0 则操作无效。
##### 3.3循环输入,用户选择y/n是够继续
for(;;){
switch(){
……
}
char answer = getchar();//从键盘中输入一个字符
if(answer == 'y' || answer == 'Y'){
printf("\nEnter the calculation\n");
scanf("%lf %c %lf", &number1, &operation, &number2);
}
if(answer == 'n' || answer == 'N'){
break; /* Go back to the beginning */
}
}
#### 4,项目源码
/*Exercise 3.4 A calculator that allows multiple calculations */
include <stdio.h>
int main()
{
double number1 = 0.0; /* First operand value a decimal number /
double number2 = 0.0; / Second operand value a decimal number /
char operation = 0;
char answer ;/ Operation - must be +, -, *, /, or % */
printf("\nEnter the calculation\n");
scanf("%lf %c %lf", &number1, &operation, &number2);
for(;;){
switch(operation)
{
case '+': // No checks necessary for add
printf("= %lf\n", number1 + number2);
break;
case '-': // No checks necessary for subtract
printf("= %lf\n", number1 - number2);
break;
case '*': // No checks necessary for multiply
printf("= %lf\n", number1 * number2);
break;
case '/':
if(number2 == 0) // Check second operand for zero
printf("\n\n\aDivision by zero error!\n");
else
printf("= %lf\n", number1 / number2);
break;
case '%': // Check second operand for zero
if((long)number2 == 0)
printf("\n\n\aDivision by zero error!\n");
else
printf("= %ld\n", (long)number1 % (long)number2);
break;
default: // Operation is invalid if we get to here
printf("\n\n\aIllegal operation!\n");
break;
}
/* The following statements added to prompt for continuing */
printf("\n Do you want to do another calculation? (y or n): ");
scanf(" %c", &answer);
if(answer == 'y' || answer == 'Y'){
printf("\nEnter the calculation\n");
scanf("%lf %c %lf", &number1, &operation, &number2); /* Go back to the beginning /
}
if(answer == 'n' || answer == 'N'){
break; / Go back to the beginning */
}
}
return 0;
}
#### 5,项目提升
能支持任意多个操作数的运算,引入运算符优先关系机制,届时更新
######[友情链接](https://github.com/apress/beg-c-5th-edition)
网友评论