gpt4 book ai didi

c - 加法和乘法 C 语言

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

为什么我在这段代码中的加法和乘法部分得到错误的答案?

#include <stdio.h>
#include <stdlib.h>

int main()
{
char x, y, z;
printf("Enter the calculation: ");
scanf("%c %c %c", &x, &y, &z);

int a = (int)x;
int b = (int)z;
}

问题出在这里:

if(y == '+'){
printf("The answer is %d", a+b);
}

这里:

else if(y == '*'){
printf("The answer is %d", a*b);
}
else{
printf("Use only +, -, /, * signs");
}
return 0;
}

最佳答案

首先要了解,您正在使用字符变量来获取用户输入,然后将它们类型转换为整数变量。这种类型转换将导致字符的 ASCII 代码值被复制到这些整数变量中。因此,即使您输入 3 + 2 ,x 将包含值 51(ASCII 代码),z 将包含值 50(ASCII 代码),答案将是 101,根据代码是正确的。ASCII码请引用http://ascii.cl/另外,您的代码中似乎存在一个小错误(这可能取决于所使用的编译器。我使用 Turbo C++,在这种情况下,在任何其他操作(如 printf)之后,它给我带来了变量声明错误。

#include <stdio.h>
#include <stdlib.h>



int main()
{
char x, y, z;
int a;
int b;


printf("Enter the calculation: ");
scanf("%c %c %c", &x, &y, &z);

a=(int) x;
b=(int) z;

if(y == '+'){
printf("The answer is %d", a+b);
}
else if(y == '*'){
printf("The answer is %d", a*b);
}
else{
printf("Use only +, -, /, * signs");
}

return 0;
}

这段代码工作正常。如果您仍然想保留相同的代码,那么只需执行此操作即可。

int a = x - '0';

它会起作用的。

关于c - 加法和乘法 C 语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43017471/

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