2

我正在尝试用 C 编写一个程序,该程序根据用户提供的输入调用两个函数之一。

如果用户输入'1',程序应该说“你选择了A”,如果用户输入'2',程序应该说“你选择了B”。我遇到的问题是,无论用户输入 1 还是 2,都会返回“您选择 A”的消息(请参见屏幕截图)。

选择 1

选择 2

这是我的代码:

include <stdio.h>

void celsiusFahrenheit()
{
    printf("You chose A");
}

void fahrenheitCelsius()
{
    printf("You chose B");
}

int main()
{
    int selection;
    printf("Please enter '1' to convert celsius to fahrenheit, or enter '2' to convert fahrenheit to celsius: ");
    scanf_s("%d", &selection);
    while (selection < 1 || selection > 2)
    {
        printf("Please enter a valid entry of either 1 or 2: ");
        scanf_s("%d", &selection);
    }
    if (selection = 1)
    {
        celsiusFahrenheit();
    }
    else
    {
        fahrenheitCelsius();
    }
}

如果您能提供任何帮助,我将不胜感激!

4

1 回答 1

0

您将一个整数常量分配给一个整数 ( selection = 1) 并检查它的真值,它始终为真。正如评论中已经指出的那样,您可以使用-Wall会警告您的选项,

warning: suggest parentheses around assignment used as truth value [-Wparentheses]

 if (selection = 1)

     ~~~~~~~~~~^~~

或者if像这样改变条件:

 if (1 == selection)

如果你在上面的语句中犯了同样的错误(赋值),即使没有-Wall选项,编译器也会产生错误,你会在程序中避免这个错误。

于 2018-11-05T06:10:11.893 回答