vendredi 31 mai 2019

Confusion with scanf() or if()

I am not so familiar with C. Therefore, maybe someone will easily find a solution, I will not mind if you share it. After entering the data in the first scanf() always gives the option else(): "Error".

I was looking for possible options for the problem. I found a lot of things like that, but nothing that to help me specifically. I think the mistake is in the strcmp(). But I can not say for sure. Will you help?

#include <stdio.h>
#include <string.h>

int main()
{
        float celsius, fahrenheit;
        char tempConvering[10];

        printf("Enter what to convert to what (F to C; C to F): ");
        scanf(" %s", &tempConvering[10]);

        if(strcmp(tempConvering, "F to C") == 0)
        {
            printf("\nEnter temperature in Fahrenheit: ");
            scanf(" %f", &fahrenheit);
            celsius = fahrenheit * 1.8 + 32;
            printf("%.2f Fahrenheits = %.2f Celsius\n", fahrenheit, celsius);
        }
        else if(strcmp(tempConvering, "C to F") == 0)
        {
            printf("\nEnter temperature in Celsius: ");
            scanf(" %f", &celsius);
            celsius = (fahrenheit - 32) / 1.8;
            printf("%.2f Celsius = %.2f Fahrenheits\n", celsius, fahrenheit);
        }
        else
        {
            puts("\nError!");
        }
}

Aucun commentaire:

Enregistrer un commentaire