jeudi 23 août 2018

Trying to write a small calculator in C but shows error

C NEWBIE ALERT!


The idea is that I ask the user to input an int, then another int, then I give them a list of the possible operations to choose from. They are required to type the name of the operation, which is then assigned to the variable operation of type char.

Then the program compares the value of the operation variable with the list of operations I mentioned earlier using if/if else statements. If it finds a match, it calls a function which returns the value of the two integers after performing the requested operation on them. If it DOESN'T find a match, it prints ("Please type a valid operation name.")

Here comes the issue. Whenever I type any value for the operation variable, EVEN if it's a valid operation name, it always prints ("Please type a valid operation name.")

enough yadda-yadda, here's the code:

#include <stdio.h>
int addNum(short int x,short int y)
{
    return x + y;
}
int subNum(short int x, short int y)
{
    return x - y;
}
int multiNum(short int x, short int y)
{
    return x * y;
}
int divNum(short int x, short int y)
{
    return x / y;
}
int calcRemainder(short int x, short int y)
{
    return x % y;
}
int main() {
    int numOne;
    int numTwo;

    char operation[10];

    printf("Please enter an integer: ");
    scanf_s("%d", &numOne);
    printf("\nPlease enter another integer: ");
    scanf_s("%d", &numTwo);
    printf("\nNow, type the type of operation you want to perform (sum, diff, multi, div, remainder): ");
    scanf_s("%s", &operation, 10);
    printf(operation);

    if (operation == "sum")
    {
        printf("Sum of %d and %d is %d", numOne, numTwo, addNum(numOne, numTwo));
    }
    else if (operation == "diff")
    {
        printf("Difference between %d and %d is %d", numOne, numTwo, subNum(numOne, numTwo));
    }
    else if (operation == "mutli")
    {
        printf("Product of multiplying %d by %d is %d", numOne, numTwo, multiNum(numOne, numTwo));
    }
    else if (operation == "div")
    {
        printf("Quotient of dividing %d by %d is %d", numOne, numTwo, divNum(numOne, numTwo));
    }
    else if (operation == "remainder")
    {
        printf("Remainder of dividing %d and %d is %d", numOne, numTwo, calcRemainder(numOne, numTwo));
    }
    else
    {
        printf("Please type a valid operation to perform: ");
    }
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire