0

I have a class exercise that ask us write a C-program to read 2 numbers from user and perform an operation based on the operator entered by the user. The Pseudocode is this.

  1. Get 2 numbers from user.
  2. Get operator from user (e.g +,-,/,*).
  3. if operator entered = +, add the 2 numbers, else if ....

This is my code:


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

int main()
{
    int x,y;
    char op;  //op is the identifier meaning operator

    printf("Enter x: ");
    scanf("%d",&x);

    printf("Enter y: ");
    scanf("%d",&y);

    printf("Enter op: ");
    scanf("%ch",&op);

    if(op == '+'){
        printf("%d + %d = %d \n",x,y,x+y);
    }else if(op == '-'){
        printf("%d + %d = %d \n",x,y,x-y);
    }else if(op == '*'){
        printf("%d + %d = %d \n",x,y,x*y);
    }else if(op == '/'){
        printf("%d + %d = %d \n",x,y,x/y);
    }else{
        printf("Invalid operator entered!\n");
    }
}

This is the output i get when i run the code

Output

I've done this before, sometimes last year and everything ran smoothly, but now it isnt. i dont know if its from my IDE or something i'm getting wrong (I use Codeblocks as my IDE for C-lang )

i've tried to change the operator from a single to character to a string but its still not working.

tadman
  • 208,517
  • 23
  • 234
  • 262
KZSY
  • 1
  • 2
  • `scanf("%ch",&op);` => `scanf("%c",&op);` – pm100 Dec 12 '22 at 23:30
  • Please post code, errors, sample data or textual output here as plain-text, not as images that can be hard to read, can’t be copy-pasted to help test code or use in answers, and are barrier to those who depend on screen readers or translation tools. You can edit your question to add the code in the body of your question. For easy formatting use the `{}` button to mark blocks of code, or indent with four spaces for the same effect. The contents of a **screenshot can’t be searched, run as code, or easily copied and edited to create a solution.** – tadman Dec 12 '22 at 23:31
  • @pm100 And then => `scanf(" %c",&op);` – Steve Summit Dec 12 '22 at 23:31

0 Answers0