Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C -- Conditional always jumping to 'Else'?

Tags:

c

temperature

I am working on learning C and am using some practice problems from the Python book I recently finished. My C book is in the mail, but I wanted to get a head start. I was putting together a simple temperature conversion program and for some reason it always jumps to the 'Else' clause in my conditional... I'm sure I'm missing something simple, but I can't seem to figure it out. Any ideas?:

#include<stdio.h>

main()
{
float temp_c, temp_f;
char convert_from[1];

printf("Convert from (c or f): ");
scanf("%c", &convert_from);

if(convert_from == "c")
{
    printf("Enter temperature in Celsius: ");
    scanf("%f", &temp_c);

    temp_f=(1.8*temp_c)+32;

    printf("The temperature in Fahreinheit is: %f \n", temp_f);
}

else if(convert_from == "f")
{
    printf("Enter temperature in Fahreinheit: ");
    scanf("%f", &temp_f);

    temp_c=(temp_f/1.8)-32;

    printf("The temperature in Celsius is: %f \n", temp_c);
}

else
    printf("Invalid choice. \n");

}
like image 321
cgc Avatar asked Jan 27 '26 12:01

cgc


1 Answers

If you are comparing characters do this:

char convert_from; 

printf("Convert from (c or f): "); 
scanf("%c", &convert_from); 

if (convert_from == 'c') 
{ 

Otherwise you can't perform the comparison with a string literal "c" (note the double quotes) like that.

like image 180
Mitch Wheat Avatar answered Jan 29 '26 01:01

Mitch Wheat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!