一个使用 C 的简单计算器,用于将华氏度转换为摄氏度,反之亦然

A simple calculator using C about conversion of Fahrenheit to Celsius, and vice versa

美好的一天!我试着用 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

strcmp用于

(answer == "CF"){

strcmp(answer, "CF") == 0

你不能在 C 中像这样比较字符串。有 strcmpstrncmp 函数。此外,此 C 字符串以 [=13=] 符号结尾,因此您的代码应如下所示:

#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;
}