mardi 26 mai 2015

C Program Skipping if Statements Even When Conditions Are Met

Trying to solve this question I have for HW but I'm stuck with one little problem. I have a series of if statements but the program just skips every if statement even when the condition is met. Ex: User wants to execute 5 - 2, instead of going to the second if statement to check for when the user entered the minus, the program just skips every single if statement.

The question is:

Consider a C program that reads two real numbers from the keyboard followed by a
character where the character can be one of the operators +, -, *, /, or % providing the
addition, subtraction, multiplication, division, or remainder respectively. Then the result
is displayed on the screen.
For example, if the user types:
2.0 3.0 %
then your code will display:
2 % 3 = 2
Note: In the above example the inputs are real numbers but the remainder only performs
an integer operation. Hence, the two real numbers must be type cast to allow computation
by remainder.
In the case where an invalid operator is entered (e.g. $) then an error message is printed
to the standard output, e.g.
Invalid entry! 

My code is:

#include <stdio.h>

int
main(void)

{
    double num1, num2, plus, minus, divide, mult, op;

    printf("Enter two numbers and an operation you would like to perform on those number: \n");
    scanf("%lf %lf %lf", &num1, &num2, &op);

    if(op=='+')
    {
        plus=(num1 + num2);

        printf("%lf + %lf = %lf", num1, num2, plus);
    }

        else if(op=='-')
        {
            minus=num1-num2;

            printf("%lf - %lf = %lf", num1, num2, minus);
        }

            else if(op=='/')
            {
                divide=num1/num2;

                printf("%lf / %lf = %lf", num1, num2, divide);
            }

                else if(op=='%')
                {
                    int num1, num2, remain;

                    remain= (num1%num2);

                    printf("%d %% %d = %d", num1, num2, remain);

                }

                    else
                    {
                        printf("Invalid entry!");
                    }                        


    return(0);
}

Would really appreciate some help on this, have been struggling for a while on such a small error.

Aucun commentaire:

Enregistrer un commentaire