输入字符后变量自动变为零

Variable is automatically becoming zero after character input

在此程序中,num1 值在 if-else 条件下变为零。我得到错误的答案,因为变量自动变为 0。这是为什么?如果我将 num1 设为 4,将 num2 设为 3。我得到的附加值为 3,它应该是 7。请帮忙解决

#include<stdio.h>
void main()
{
    int num1, num2, answer;
    char type;

    printf("Enter num1\n");
    scanf("%d",&num1);
    printf("Enter num2\n");
    scanf("%d",&num2);
    printf("type a for addition or s for subtraction\n");
    scanf("%s",&type);

    if(type == 'a')
    {
        answer = num1 + num2;
        printf("answer is %d \n",answer);
    }
    else if(type == 's')
    {
        answer = num1 - num2;
        printf("answer is %d \n",answer);
    }
    else
    {
        printf("enter a or s");
    }
}
  • 使用%c进行字符输入。
  • 在 if-else 语句中使用 answer 变量。
#include<stdio.h>
void main()
{
    int num1, num2, answer;
    char type;

    printf("Enter num1\n");
    scanf("%d",&num1);
    printf("Enter num2\n");
    scanf("%d",&num2);
    printf("type a for addition or s for subtraction\n");
    scanf(" %c",&type);

    if(type == 'a')
    {
        answer = num1 + num2;
        printf("answer is %d \n",answer);
    }
    else if(type == 's')
    {
        answer = num1 - num2;
        printf("answer is %d \n",answer);
    }
    else
    {
        printf("enter a or s");
    }
}

解决方案1:You 在接收用户对类型变量的输入时可以使用 %c 而不是 %s。

解决方法2:You可以使用%s来获取类型变量的输入值。但是在 if 和 else if 语句中进行比较时,您可以使用 C String 模块的内置函数片段:=if(type.equals('a'))。在这种情况下,您应该使用 equals() 方法进行比较

#include<stdio.h>
void main()
{
    int num1, num2, answer;
    char type;

    printf("Enter num1\n");
    scanf("%d",&num1);
    printf("Enter num2\n");
    scanf("%d",&num2);
    printf("type a for addition or s for subtraction\n");
    scanf("%c",&type);

    if(type == 'a')
    {
        answer = num1 + num2;
        printf("answer is %d \n",add);
    }
    else if(type == 's')
    {
        answer = num1 - num2;
        printf("answer is %d \n",sub);
    }
    else
    {
        printf("enter a or s");
    }
}

add printf("answer is %d \n", add); 中使用的变量未在您的程序中定义。 sub 也不是。它应该给出一个编译错误。您是否关闭了编译错误?试试这个代码...

#include<stdio.h>
void main()
{
    int num1, num2, answer;
    char type;

    printf("Enter num1\n");
    scanf("%d",&num1);
    printf("Enter num2\n");
    scanf("%d",&num2);
    printf("type a for addition or s for subtraction\n");
    scanf("%c",&type);

    if(type == 'a')
    {
        answer = num1 + num2;
        printf("answer is %d \n",answer);
    }
    else if(type == 's')
    {
        answer = num1 - num2;
        printf("answer is %d \n",answer);
    }
    else
    {
        printf("enter a or s");
    }
}