【问题标题】:C if statement not recognising scan input [duplicate]C if语句无法识别扫描输入[重复]
【发布时间】:2017-07-10 01:46:18
【问题描述】:

所以我正在尝试制作一个简单的温度转换器。对我来说一切都很好,但我不知道为什么扫描输入没有被识别。 感谢您的宝贵时间。

    #include <stdio.h>
    exercise1(){
        float a;
        char tem;
        printf("--- Temperature Converter ---\n");
        printf("Please enter a temperature: ");
        scanf("%f", &a);
        printf("\nWould you like to convert to Celsius or Fahrenheit? (c or f)");
        scanf("%c", &tem); getchar();
        if (tem == 'c'){
            a = ((float)a-32) * 5.0f/9.0f;
            printf("\nYour temperature is %g\n", &a);
        }
        else if (tem == 'f'){
            a = (float)a * 9.0f/5.0f + 32;
            printf("\nYour temperature is %g\n", &a);
        }
        else
            printf("\nPlease enter a valid conversion type!\n");
        }
    }

【问题讨论】:

  • printf("\nYour temperature is %g\n", &amp;a); remove &amp; --> printf("\nYour temperature is %g\n", a);
  • 可能是因为您在它之后调用了getchar。顺便说一句,有了float a,后面的代码就不需要(float)a(但这纯粹是语义上的)。
  • 谢谢,我把所有的答案都结合起来了。

标签: c if-statement scanf equals-operator


【解决方案1】:

scanf() 的问题是,当您输入一个空格以完成插入温度时,该空格将被插入到 tem。 为了防止它,在scanf()之前使用getchar(),如下所示。

注意:在检查给您的答案时,我看到有人建议您使用“%c”而不是“%c”。这是个好主意,而且效果很好。请注意,如果您更喜欢此解决方案,则不应使用 getchar()

此外,我还发现了几个错误: 1.使用printf()时,不应该发送&a,而是发送a。 printf() 不需要指针,而是变量。 (编译时注意警告) 2. 使用 %f 扫描浮点数,而不是 %g 3.你在最后一个else之后使用了太多的}(只需要一个,关闭函数)

#include <stdio.h>
void main(){
        float a;
        char tem;
        printf("--- Temperature Converter ---\n");
        printf("Please enter a temperature: ");
        scanf("%f", &a);
        printf("\nWould you like to convert to Celsius or Fahrenheit? (c or f)");
        getchar();
        scanf("%c", &tem);
        if (tem == 'c'){
                a = ((float)a-32) * 5.0f/9.0f;
                printf("\nYour temperature is %f\n", a);
        }
        else if (tem == 'f'){
                a = (float)a * 9.0f/5.0f + 32;
                printf("\nYour temperature is %f\n", a);
        }
        else
                printf("\nPlease enter a valid conversion type!\n");}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-05
    • 2020-02-15
    • 1970-01-01
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多