如何解决用 C 语言编程的计算器
我正在用 C 编写一个计算器,但它需要像 1+2*9/5 这样的输入。 我不是 C 专家,所以我想我可以问用户他有多少个数字(例如假设 4),然后问 3 次“输入数字,输入运算符”和 1 次“输入数字”。然后将所有输入分别放入一个空数组,然后通过循环遍历数组来执行操作。但当然,我有问题。
#include <stdio.h>
int main(void) {
int how_many;
printf("How many numbers do you have to calculate?");
scanf("%d",&how_many);
int number_entry = how_many; // for example 1+2*9/5 has 4 numbers
int operator_entry = how_many - 1; // and 3 operators
int number_in;
char operator_in;
int all_inputs[(number_entry + operator_entry)];
for (int j = 0; j < operator_entry; j++) {
printf("Enter the number : ");
scanf("%d",&number_in);
all_inputs[j] = number_in;
printf("\n");
printf("Enter the operation as + for add,- for substract,* for "
"multiply and / for division");
scanf(" %c",&operator_in);
all_inputs[j + 1] = operator_in;
}
printf("Enter the number : ");
scanf("%d",&number_in);
all_inputs[operator_entry + 1] = number_in;
for (int k = 0; k < (2 * how_many) - 1; k++)
printf("%s\n",all_inputs[k]);
return 0;
}
正如您从代码中看到的那样,循环遍历代码以将输入附加到数组中是行不通的,因为我正在这样做
j=0
给 all_inputs[0] 添加一个数字
将运算符附加到 all_inputs[0+1]
j=1
现在,运算符将被替换为数字。
另一个问题是,它只显示“输入数字”一次,然后循环“输入运算符”。
如果您知道任何其他方法可以做到这一点,请告诉我。再说一次,我不是 C 语言专家。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。