Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
简单IF语句scanf_C_If Statement_Scanf - Fatal编程技术网

简单IF语句scanf

简单IF语句scanf,c,if-statement,scanf,C,If Statement,Scanf,对于一项作业,我被要求创建一个小程序,要求用户输入确定他们希望操作的转换器。我的问题是,在用户输入他们希望使用的转换器(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")

对于一项作业,我被要求创建一个小程序,要求用户输入确定他们希望操作的转换器。我的问题是,在用户输入他们希望使用的转换器(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);
}


}
#包括
int main()
{
漂浮厘米;
浮动英寸;
int操作;
printf(“您好,欢迎使用英寸到厘米转换器。\n”);
printf(“通过输入相应的数字从下面的选项中选择:\n”);
printf(“英寸到厘米转换器(1)\n”);
printf(“厘米到英寸转换器(2)\n”);
scanf(“&d”和&operation);
如果(操作==1)
{
printf(“请输入要转换的英寸数:\n”);
扫描频率(“%f”和英寸);
厘米=英寸*2.54;

如果(英寸这里有两个问题。首先:

scanf("&d", &operation);
有一个输入错误,“&d”应该是“%d”,这就是为什么您会立即收到两次提示。您想要:

scanf("%d", &operation);
其次是:

}
else if (operation == 2);
{
立即结束
else
块。因此大括号中的块将始终运行。请清除

}
else if (operation == 2)
{
更好的是:

} else if (operation == 2) {

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

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