Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Basic Calculator - Issue with else if and Y/N continuation logic [closed]

Tags:

c

#include <stdio.h>

int main()
{
    float num1;
    float num2;
    float result;
    char op;
    char yn;

    printf("Enter the first number: \n");
    scanf("%f\n", &num1);

    printf("Select the operator((+ , - , x , /)\n ");
    scanf("%c\n" , &op);

    printf("Enter the second number: \n");
    scanf("%f\n", &num2);

    if (op == '-')
    {
        result = num1 / num2;
    }
    else if (op == '+')
    {
        result = num1 + num2;
    }
    else if (op == 'x' || '.')
    {
        result = num1 * num2;
    }
    else (op == '/')
    {
        result = num1 / num2;
    }
    printf("Result: %lf, " &result);

    return 0;

    printf("Do you want to continue (Y/N) ?");
    scanf("%c\n", &yn );

    if (yn == 'Y' || 'y')
    {
        return main;
    }
    else (yn == 'N' || 'n')
    {
      return 0;
    }


return 0;
}

I am new to C and trying to create a basic calculator. I have encountered errors in the else if statements and the part where I ask the user if they want to continue (Y or N).

My goal is:

  1. Perform a basic arithmetic operation based on user input.

  2. After displaying the result, ask the user if they want to continue.

  3. If the user enters Y, the program should restart and ask for new inputs.

  4. If the user enters N, the program should exit.

Issues I Encounter:

  1. Errors in else if Statements - I might have syntax issues in the structure.

  2. Y/N Continuation Logic Not Working Properly - It either skips the input or behaves unexpected

What I Need: Help in fixing any syntax issues. Ensuring the loop correctly asks if the user wants to continue and behaves as expected.

like image 777
Bartoo Y. Avatar asked Oct 27 '25 13:10

Bartoo Y.


2 Answers

You can use a do-while loop and wrap your whole code around it. That way you won't need to check it using if-else.

#include <stdio.h>

int main() {
    float num1, num2, result;
    char op, yn;

    do {
        // Read first number
        printf("Enter the first number: ");
        scanf("%f", &num1);

        // Read operator; the space before %c skips any leftover whitespace
        printf("Select the operator (+, -, x, /): ");
        scanf(" %c", &op);

        // Read second number
        printf("Enter the second number: ");
        scanf("%f", &num2);

        // Perform the calculation based on the operator
        if (op == '+') {
            result = num1 + num2;
        } else if (op == '-') {
            result = num1 - num2;
        } else if (op == 'x' || op == 'X' || op == '*') {
            result = num1 * num2;
        } else if (op == '/') {
            // Check for division by zero
            if (num2 == 0) {
                printf("Error: Division by zero!\n");
                // Skip the rest of this iteration and ask again.
                continue;
            }
            result = num1 / num2;
        } else {
            printf("Invalid operator!\n");
            // Skip this iteration if the operator is invalid.
            continue;
        }

        // Display the result
        printf("Result: %f\n", result);

        // Ask if the user wants to continue
        printf("Do you want to continue (Y/N)? ");
        scanf(" %c", &yn);

    } while (yn == 'Y' || yn == 'y');

    return 0;
}
like image 68
Ronit Gandhi Avatar answered Oct 29 '25 05:10

Ronit Gandhi


The return from scanf should always be checked. If you try to scan a double and the user enters abc, the scan fails and abc is left in the input stream.
scansets are very useful. %1[ynYN] will scan one character that must be y, Y, n or N. %*[^\n] scans and discards everything not a newline.
Functions are also useful. scandouble ( ) can be called to obtain the two floating point values.
switch is also useful and can replace multiple else statements.

#include <stdio.h>
#include <stdlib.h>

double scandouble ( ) {
    char nl[2] = "";
    int scanned = 1;
    double value = 0.0;

    do {
        if ( ! scanned) {
            printf ( "try again\n");
        }
        scanned = scanf ( "%lf", &value);
        if ( EOF == scanned) {
            fprintf ( stderr, "EOF\n");
            exit ( 1);
        }
        scanf ( "%*[^\n]"); // scan and discard everything not a newline
        scanf ( "%1[\n]", nl); // scan a newline
    } while ( ! scanned);
    return value;
}

char scanoperator ( ) {
    int scanned = 1;
    char operator[2] = "";
    char nl[2] = "";

    do {
        if ( ! scanned) {
            printf ( "try again\n");
        }
        scanned = scanf ( "%1[x/+-]", operator);
        if ( EOF == scanned) {
            fprintf ( stderr, "EOF\n");
            exit ( 1);
        }
        scanf ( "%*[^\n]"); // scan and discard everything not a newline
        scanf ( "%1[\n]", nl); // scan a newline
    } while ( ! scanned);
    return operator[0];
}

char scanyn ( ) {
    int scanned = 1;
    char yn[2] = "";
    char nl[2] = "";

    do {
        if ( ! scanned) {
            printf ( "try again\n");
        }
        scanned = scanf ( "%1[ynYN]", yn);
        if ( EOF == scanned) {
            fprintf ( stderr, "EOF\n");
            exit ( 1);
        }
        scanf ( "%*[^\n]"); // scan and discard everything not a newline
        scanf ( "%1[\n]", nl); // scan a newline
    } while ( ! scanned);
    return yn[0];
}

int main ( void) {
    double num1 = 0.0;
    double num2;
    double result;
    char op;
    char yn;

    while ( 1){
        printf ( "Enter the first number: \n");
        num1 = scandouble ( );

        printf ( "Select the operator((+ , - , x , /)\n ");
        op = scanoperator ( );

        printf ( "Enter the second number: \n");
        num2 = scandouble ( );

        switch ( op) {
            case '/':
                result = num1 / num2;
                break;
            case '+':
                result = num1 + num2;
                break;
            case 'x':
                result = num1 * num2;
                break;
            case '-':
                result = num1 - num2;
                break;
        }
        printf ( "Result: %lf\n", result);

        printf ( "Do you want to continue (Y/N) ?");
        yn = scanyn ( );

        switch ( yn) {
            case 'n':
            case 'N':
                return 0;
            case 'y':
            case 'Y':
                break;
        }
    }

    return 0;
}
like image 37
xing Avatar answered Oct 29 '25 04:10

xing



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!