它应该添加 2 个数字,然后我添加更多运算符
#include <stdio.h>;
#include <string.h>;
main()
{
int num1;
int num2;
int end;
char op[4];
char plus[4] = "plus";
printf ("What is your first number?\n ");
scanf ("%d", &num1);
printf ("What is your second number?\n ");
scanf ("%d", &num2);
printf ("What operator would you like to use\n ");
scanf ("%c", &op);
if (op == plus){
end = num1 + num2;
printf ("%d", end);
}
}
[result when I run it](https://i.sstatic.net/jKqZBkFd.png)
我尝试更改数组编号,更改标题,添加更多=但我不知道
主要错误是您使用
%c
来读取末尾的字符串。它读取紧接在 num2
读取的整数之后的字符,即可能是 行尾 字符。要读取字符串,必须使用 %s
而不是 %c
。另外,字符串(char
的数组)已经是一个地址,所以你不应该传递数组的地址(&op
),而应该传递数组本身(op
);在这种情况下没关系,因为数组的地址与数组的值相同,但类型错误,所以请写:
scanf("%s", op);
还有另外 2 个错误。
char
数组中包含 4 个字符的字符串,必须为数组指定大小 5,因为在 C 中,字符串以 end of string 字符终止(其代码为零,通常写为 '\0'
) .==
进行字符串比较。使用==
只能进行地址比较。您必须使用strcmp
:
if (strcmp(op, plus) == 0) {
strcmp
接受 2 个字符串作为参数,如果第一个字符串最小,则返回 -1;如果相等,则返回 0;如果第一个字符串最大,则返回 1(这是比较函数的常见约定)。