1

this is a c program to make a calulator but when i run it asks me for numbers but after it automatically shows the sum and doesnt ask for operator.

#include<stdio.h>
int main()
{
   char op;
   double n1,n2;
   printf("enter first number");
   scanf("%f",&n1);
   printf("enter second number");
   scanf("%f",&n2);
   printf("enter operation");
   scanf("%c",&op);
   if (op=="+"){
       printf("the sum = %f",n1+n2);
   }
   else if (op=="-"){
       printf("the difference= %f",a-b);
   }
   else if (op=="*"){
       printf("the product= %f", a*b);
   }
   else if (op=="/"){
       printf("the quotient= %f",a/b);
   }

   return 0;
}

the program end

FireRecon
  • 37
  • 1

1 Answers1

0

Another problem (beside the scanf("%c",&op);) is that "x" is considered as a string while 'x' is a character (see this related question).

This is working:

#include <stdio.h>

int main()
{
   char op;
   double n1,n2;
   printf("enter first number");
   scanf("%f",&n1);
   printf("enter second number");
   scanf("%f",&n2);
   printf("enter operation");
   scanf(" %c",&op);
   if (op=='+'){
       printf("the sum = %f",n1+n2);
   }
   else if (op=='-'){
       printf("the difference= %f",n1-n2);
   }
   else if (op=='*'){
       printf("the product= %f", n1*n2);
   }
   else if (op=='/'){
       printf("the quotient= %f",n1/n2);
   }
   else{
     printf("Operator '%c' is incorrect.", op);
   }

   return 0;
}
Jona
  • 1,218
  • 1
  • 10
  • 20