gpt4 book ai didi

C 程序 int 变量值在读取 Char 值后发生变化

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

我是 C 编程新手,刚刚创建了一个小型计算器应用程序,但我注意到,当我在读取 Int 值后读取 char 值时,下一个直接 Int 变量会发生变化。到底是什么原因造成这种情况呢?这是我的代码

#include <stdio.h>

int main(){
int num1;
int num2;
char opr;
int ans;

printf("Enter the first number : ");
scanf("%d", &num1);

printf("Enter the second number : ");
scanf("%d", &num2);

printf("Enter the operater : ");
scanf("%s", &opr);

printf("%d \n", num1);
printf("%d \n", num2);

switch(opr) {
case '+':
ans=num1+num2;
printf("The addtion of %d and %d is %d", num1, num2, ans);
printf("\n");
break;

case '-':
ans=num1-num2;
printf("The substractuon of %d from %d is %d", num2, num1, ans);
printf("\n");
break;

case '*':
ans=num1*num2;
printf("The multiplication of %d and %d is %d", num1, num2, ans);
printf("\n");
break;

case '/':
ans=num1/num2;
printf("The substraction of %d from %d is %d", num1, num2, ans);
printf("\n");
break;
}

return 0;
}

最佳答案

这里你必须使用 scanf("%c", &opr); 而不是 scanf("%s", &opr); 因为 oprchar 你必须使用%c,其中 %s 用于扫描 String 。然后出现未处理的问题 '\n' 出现问题。因此,在 %c 前面添加一个额外的 '\n' 。因此该语句变为 scanf("\n%c", &opr);;

修改后的代码:-

#include <stdio.h>

int main()
{
int num1;
int num2;
char opr;
int ans;

printf("Enter the first number : ");
scanf("%d", &num1);

printf("Enter the second number : ");
scanf("%d", &num2);

printf("Enter the operater : ");
scanf("\n%c", &opr); // not scanf("%s", &opr);

printf("%d \n", num1);
printf("%d \n", num2);

switch (opr)
{
case '+':
ans = num1 + num2;
printf("The addtion of %d and %d is %d", num1, num2, ans);
printf("\n");
break;

case '-':
ans = num1 - num2;
printf("The substractuon of %d from %d is %d", num2, num1, ans);
printf("\n");
break;

case '*':
ans = num1 * num2;
printf("The multiplication of %d and %d is %d", num1, num2, ans);
printf("\n");
break;

case '/':
ans = num1 / num2;
printf("The substraction of %d from %d is %d", num1, num2, ans);
printf("\n");
break;
}

return 0;
}

输出:-

Enter the first number : 3
Enter the second number : 4
Enter the operater : *
3
4
The multiplication of 3 and 4 is 12

关于C 程序 int 变量值在读取 Char 值后发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51263894/

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