C - printf 里面的 "if"语句不显示

标签 c

我试图让 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);
}

关于C - printf 里面的 "if"语句不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24308997/

相关文章:

C- Unix 套接字 - 非阻塞读取

c - 使用 strcpy 时出现访问冲突?

c - 解释这个 C 程序的输出?

CMSIS 和外围设备驱动程序

c - 如何在 C 中使用模数将 Float 转换为 Int?

c - 同时使用代码页 437 和 setlocale

c - 显示字符串中每个字符的二进制

c - 我无法将节点插入二叉搜索树

在linux C上复制文件

c - Fortran 77 如何分配公共(public) block 变量?