【问题标题】:A simple calculator using C about conversion of Fahrenheit to Celsius, and vice versa一个使用 C 的简单计算器,用于将华氏温度转换为摄氏温度,反之亦然
【发布时间】:2021-10-30 07:31:14
【问题描述】:

美好的一天!我尝试使用 C 制作一个简单的计算器,用于我的第一个关于华氏到摄氏度之间转换的项目,反之亦然。但它不起作用,有人可以告诉我我想念什么吗?

这是我的代码:

#include <stdio.h>

int main()
{
double temp, fahrenheit, celsius;
char answer[2];

printf("Type 'CF' if you want to convert from celsius to fahrenheit, and 'FC' if you want to convert from fahrenheit to celcius: ");
fgets(answer, 2, stdin);

fahrenheit = (temp * 1.8) + 32;
celsius = (temp - 32) * 0.5556;
if(answer == "CF"){
    printf("Type the temperature here: ");
    scanf("%lf", &temp);
    printf("Answer: %f", fahrenheit);
}
else if(answer == "FC"){
    printf("Type the temperature here: ");
    scanf("%lf", &temp);
    printf("Answer: %f", celsius);
}
return 0;

}

calculator

【问题讨论】:

    标签: if-statement calculator


    【解决方案1】:

    您不能在 C 中比较这样的字符串。有 strcmpstrncmp 函数。除了这个 C 字符串以 \0 符号结尾,所以你的代码应该是这样的:

    #include <stdio.h>
    #include <string.h>
    
    int main()
    {
        double temp, fahrenheit, celsius;
        char answer[3];
    
        printf("Type 'CF' if you want to convert from celsius to fahrenheit, and 'FC' if you want to convert from fahrenheit to celcius: ");
        fgets(answer, 3, stdin);
    
        fahrenheit = (temp * 1.8) + 32;
        celsius = (temp - 32) * 0.5556;
    
        if (strcmp(answer, "CF") == 0) {
            printf("Type the temperature here: ");
            scanf("%lf", &temp);
            printf("Answer: %f", fahrenheit);
        } else if (strcmp(answer, "FC") == 0){
            printf("Type the temperature here: ");
            scanf("%lf", &temp);
            printf("Answer: %f", celsius);
        }
    
        return 0;
    }
    

    【讨论】:

    • 它工作!非常感谢你告诉我出了什么问题,干杯!!!
    【解决方案2】:

    strcmp 用于

    (answer == "CF"){
    

    strcmp(answer, "CF") == 0
    

    【讨论】:

    • 这个方法也可以,非常感谢你的努力!!。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-08
    • 1970-01-01
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    相关资源
    最近更新 更多