gpt4 book ai didi

计算器程序问题

转载 作者:行者123 更新时间:2023-11-30 20:29:04 26 4
gpt4 key购买 nike

我正在尝试找出该程序无法运行的原因。它应该执行类似的操作

5 * 4 = 20 4 + 2 * 8 = 20 6/3 - 2 = 0。

但是,事情并不顺利。

说明是:

Write a C program called calculate that performs simple arithmetic operations. The program takes 3 or 5 arguments from the command line.

我不知道现在该怎么办。

int calc(int x, char op, int y) {
if (op == '+') {
return (x+y);
}
if (op == '-') {
return (x-y);
}
if (op == 't') {
return (x*y);
}
if (op == '/') {
return (x/y);
}
}

int main(int argc, char *argv[]) {
int a,b,c,result,doOp;
char op1, op2;

if (argc == 4 || argc == 6) {
a = atoi(argv[1]);
b = atoi(argv[3]);
op1 = *argv[2];
} else {
printf("Wrong number of arguments!");
return 0;
}

if (argc == 6) {
c = atoi(argv[5]);
op2 = *argv[4];

if ((op1 == '+' || op1 == '-') && (op2 == '/' || op2 == 't')) {
result = calc(a, op1, calc(b, op2, c));
printf("%d", result);
}

if ((op2 == '+' || op2 == '-') && (op1 == '/' || op1 == 't')) {
result = calc((calc(a, op1, b)), op2, c);
printf("%d", result);
} else {
result = calc((calc(a, op1, b)), op2, c);
printf("%d", result);
}
}

if (argc == 4) {
result = calc(a, op1, b);
printf("%d", result);
}
return 0;
}

最佳答案

给你阿里雷扎。问题有几个,但主要的一个是您检查中缺少“else”以查看要使用哪个计算器排序。

int calc(int x, char op, int y) {

if (op == '+') {
return (x+y);
}
if (op == '-') {

return (x-y);
}
if (op == 't') {

return (x*y);
}
if (op == '/') {
return (x/y);
}

printf("Unknown operator!"); // added error check
}

int main(int argc, char *argv[]) {

int a,b,c,result,doOp;
char op1, op2;

if (argc == 4 || argc == 6) {

a = atoi(argv[1]);
b = atoi(argv[3]);
op1 = *argv[2];

} else {
printf("Wrong number of arguments!");
return 0;
}

if (argc == 6) {
c = atoi(argv[5]);
op2 = *argv[4];

if ((op1 == '+' || op1 == '-') && (op2 == '/' || op2 == 't')) {

result = calc(a, op1, calc(b, op2, c));
printf("%d", result);
}
// added else if
else if ((op2 == '+' || op2 == '-') && (op1 == '/' || op1 == 't')) {

result = calc((calc(a, op1, b)), op2, c);
printf("%d", result);
}
else {
result = calc((calc(a, op1, b)), op2, c);
printf("%d", result);
}
}

if (argc == 4) {

result = calc(a, op1, b);
printf("%d", result);
}

return 0;
}

关于计算器程序问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59144970/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com