【问题标题】:Simple IF statement scanf简单的 IF 语句 scanf
【发布时间】:2019-03-17 19:32:24
【问题描述】:

对于一项任务,我被要求创建一个小程序,该程序要求用户输入确定他们希望操作的转换器。我的问题是为什么程序不要求用户输入,在他们输入他们希望使用的转换器(1 或 2)之后。它不调用scanf,而是一次性运行整个语句。

#include <stdio.h>

int main()
{
float cm;
float inches;
int operation;

printf("Hello and welcome to the Inches to Centimetres converter. \n");
printf("Choose from the options below by entering the corresponding number:\n");
printf("Inches to CM converter (1)\n");
printf("CM to Inches converter (2)\n");
scanf("&d", &operation);

if (operation == 1)
{
    printf("Please enter the amount of Inches you wish to convert : \n");
    scanf("%f", &inches);

    cm = inches * 2.54;


    if (inches <= 0)
        {
        printf("Invalid number");
        }
    else
        printf("%f inches is equal to %f centimetres.", inches, cm);
}
else if (operation == 2);
{
    printf("Please enter the amount of Centimetres you wish to convert : ");
    scanf("%f", &cm);

    inches = cm / 2.54;


    if (cm <= 0)
        {
        printf("Invalid number");
        }
    else
        printf("%f centimetres is equal to %f inches.", cm, inches);
}


}

输出

【问题讨论】:

  • 一个完整的程序不属于这里,即使它很简单。每个人都需要学习调试:如果它不起作用插入printf() 语句来验证中间结果(从长远来看,学习使用调试器)。这应该揭示哪个语句不像您期望的那样工作。如果您仍然无法解决它,请编写一个最小的演示程序来演示这个行为不端的语句并在此处提问。 (实际上我的gcc 编译器会立即警告你的错误。你似乎使用了另一个编译器,检查它是否给你警告或者你是否可以让它发出警告。)
  • 我认为@UweGeuder 想说的是*欢迎来到 StackOverflow!这是一个很好的问题。”

标签: c if-statement scanf


【解决方案1】:

这里有两个问题。第一:

scanf("&d", &operation);

有一个错字,“&d”应该是“%d”,这就是为什么你会立即收到两次提示。你想要:

scanf("%d", &operation);

第二个是:

}
else if (operation == 2);
{

; 立即结束 else 块。因此大括号中的块将始终运行。摆脱;

}
else if (operation == 2)
{

更好:

} else if (operation == 2) {

以这种方式格式化大括号实际上可以消除这种类型的错误。

【讨论】:

  • 我已经看到很多if (...); { 在同一行带有大括号。
猜你喜欢
  • 2020-02-22
  • 2022-01-26
  • 1970-01-01
  • 1970-01-01
  • 2017-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多