Home > Software design >  A simple calculator using C about conversion of Fahrenheit to Celsius, and vice versa
A simple calculator using C about conversion of Fahrenheit to Celsius, and vice versa

Time:10-31

Good day! I tried to make a simple calculator using C for my first project about conversion between Fahrenheit to Celsius, and vice versa. But it's not working, can someone tell me what I miss?

Here's my code:

#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

CodePudding user response:

Use strcmp for

(answer == "CF"){

i.e.

strcmp(answer, "CF") == 0

CodePudding user response:

You can't compare strings like this in C. There strcmp and strncmp functions. Besides this C strings are ended with \0 symbols, so your code should be something like this:

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