c - 使用 getchar() 在 C 中计算数学表达式
问题描述
我被分配了一项学校任务。在这个任务中,我必须用 C 语言创建一个程序,它从用户那里读取一个数学表达式作为输入并返回它的结果。例如,输入必须是 30 + 400,在这种情况下,输出必须是 30 和 400 相加的结果,即 430。程序必须除了加法和其他数学运算(减法、乘法、除法)。每个表达式必须在一行中读取,并且我不允许在我的代码中使用数组或任何其他复杂的数据结构。我尝试了一些方法来解决这个任务,但我不明白如何将数字与运算符分开,以便计算表达式。这是我写的:
#include <stdio.h>
int main(){
int ch,result;
int plus;
int minus;
int mult;
int div;
while((ch = getchar())!= EOF){
plus = 0;
minus = 0;
mult = 0;
div = 0;
if (ch != '\n'){
if (ch >= '0' && ch <='9'){ //Checks if the character is a number
result += ch;
}else if(ch== '+'){//Checks if the character is an operator
plus =1;
}else if(ch== '-'){
minus = 1;
}else if(ch == '*'){
mult = 1;
}else if(ch== '/'){
div = 1;
}
}
printf("%d\n",result);
}
}
任何建议或想法都会非常有帮助。PS我很抱歉我的英语,如果我用适当的术语来描述这个问题。
解决方案
getchar
返回ASCII
您需要将其转换为十进制的值。
您可以使用两个integers
来存储输入的数字并对其进行操作。
例子:
int num1 = 0,num2 = 0;
char op;
int state = 0;
while((ch = getchar())!= EOF){
if (ch != '\n'){
if (ch >= '0' && ch <='9'){ //Checks if the character is a number
if (state == 0)
num1 = num1*10 + ch- '0'; // Convert ASCII to decimal
else
num2 = num2*10 + ch- '0'; // Convert ASCII to decimal
}else {
/* Operator detected now start reading in second number*/
op = ch;
state = 1;
}
}
else {
int result =0;
switch(op)
{
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
}
printf("%d\n",result);
num1 = 0;
num2 = 0;
state = 0;
}
推荐阅读
- excel - 如何使用读取单元格并将其与图像文件名匹配的宏来更改 Excel 中的图像?
- c - AVL Tree单元测试,获取没有父节点的节点高度
- sql - 联合和右连接不适用于缺少的材料
- php - 尝试使用正确信息登录时出错
- r - 如何使用匹配函数的输出来编写基于索引行值的函数
- azure-virtual-network - 在内部部署 Azure 应用程序
- python - 使用进程工作者关闭 uwsgi/gunicorn 时,可用内存(免费)急剧下降和 CPU 峰值
- c++ - 函数执行完成后,如何使函数内部分配的内存保持分配状态?
- tsql - 通过 MS Access 中的数据表和子数据表计算总计
- amazon-web-services - 在 Athena 中查询另一个 AWS 账户的 S3 存储桶中的数据时访问被拒绝