簡體   English   中英

簡單的IF語句scanf

[英]Simple 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");
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);
}


}

產量

這里有兩個問題。 第一:

scanf("&d", &operation);

有一個錯字,“&d”應為“%d”,這就是為什么您會立即得到兩次提示的原因。 你要:

scanf("%d", &operation);

其次是:

}
else if (operation == 2);
{

; 立即結束else塊。 因此,大括號中的塊將始終運行。 擺脫;

}
else if (operation == 2)
{

更好的是:

} else if (operation == 2) {

用這種方式格式化花括號實際上將消除這種類型的錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM