dimanche 4 novembre 2018

C: Combining while and if statements

I'm trying to write a program in C which calls one of two functions, based on the input provided by the user.

The program should say "you selected A" if the user enters '1', and "you selected B" if the user enters '2'. The problem I have is that the message "you selected A" is returned whether the user enters 1 or 2 (see screenshots).

Selection 1

Selection 2

Here is my code:

include <stdio.h>

void celsiusFahrenheit()
{
    printf("You chose A");
}

void fahrenheitCelsius()
{
    printf("You chose B");
}

int main()
{
    int selection;
    printf("Please enter '1' to convert celsius to fahrenheit, or enter '2' to convert fahrenheit to celsius: ");
    scanf_s("%d", &selection);
    while (selection < 1 || selection > 2)
    {
        printf("Please enter a valid entry of either 1 or 2: ");
        scanf_s("%d", &selection);
    }
    if (selection = 1)
    {
        celsiusFahrenheit();
    }
    else
    {
        fahrenheitCelsius();
    }
}

I would be grateful for any help you can give!

Aucun commentaire:

Enregistrer un commentaire