簡體   English   中英

C-“ if”語句中的printf不顯示

[英]C - printf inside “if” statement doesn't show

我正在嘗試在if語句中顯示此printf ,但事實並非如此。 這是代碼,我突出顯示了printf部分。

char conv;
float cel;

printf("Enter what you'd like converted: \n\t1.Celcius to Fahrenheit\n\t2.Inch to CM\n\t3.CM to Inch\n");
scanf_s("%c", &conv);

// This one
if (conv == '1')
    printf("Please enter amount of Celcius: \n");
scanf_s("%f", &cel);

float fahr;
fahr = 33.8 * cel;

printf("Conversion of %f Celsius is %f Fahrenheit", cel, fahr);

getch();
return 0;

這是什么原因呢?

In looking at the line: scanf_s("%c", &conv);  
I see the function scanf_s(), 
which in not in any C library that I'm familiar with.

However, the function scanf(), which is in the C libraries, 
has the following prototype and usage:

int scanf(const char *format, ...)

where the return value is the number of items in the variable parameter list '...'
that were actually filled from the input.

I.E. your code should, after the call to scanf_s() check the return code
those value should be 1 in your example.

Then you have this code:

if (conv == '1')
    printf("Please enter amount of Celcius: \n");
scanf_s("%f", &cel);

supposedly with the idea that all those following lines would be 
enclosed in the 'if' block.
however, only the first line following the 'if' is actually part of the
'if' block.
To correct this problem, write the code using braces to delineate
the 'if' block, like this:

if (conv == '1')
{
    printf("Please enter amount of Celcius: \n");
    scanf_s("%f", &cel);

    float fahr;
    fahr = 33.8 * cel; // BTW: this is not the correct conversion formula

    printf("Conversion of %f Celsius is %f Fahrenheit", cel, fahr);
}

暫無
暫無

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

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