【发布时间】:2019-04-08 07:54:54
【问题描述】:
我正在尝试用 C 编写一个程序,该程序根据用户提供的输入调用两个函数之一。
如果用户输入“1”,程序应该说“你选择了 A”,如果用户输入“2”,程序应该说“你选择了 B”。我遇到的问题是,无论用户输入 1 还是 2,都会返回消息“您选择 A”(请参见屏幕截图)。
这是我的代码:
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();
}
}
如果您能提供任何帮助,我将不胜感激!
【问题讨论】:
-
selection = 1是赋值而不是相等比较 (==)。如果你在编译时使用了一些防御性标志(如 gcc/clang 的-Wall),你的编译器会警告你。 -
将
if (selection = 1)更改为if (selection == 1)。这是一个常见的错误。增加编译器警告,并可能将代码设置为if (1 == selection),以在键入错误时产生错误。 -
@PSkocik Clang 有
-Weverything。 -
谢谢,伙计们。这真的很有帮助!
-
@FiddlingBits:
-Weverything警告太多——我不认为它可用于生产代码,因为它会抱怨,例如,如果您使用#define _XOPEN_SOURCE 700启用 POSIX 功能,因为名称保留用于实现。是的,我知道它是;这就是我使用它的原因!它必须经过调整才能真正与许多-Wno-xyz选项一起使用。我使用-Weverything -Wno-padded -Wno-vla -Wno-reserved-id-macro -Wno-documentation-unknown-command让事情对我来说足够健康。我也使用-Werror,所以我不会在编译时出现任何警告。
标签: c function if-statement while-loop