C programing DOUBT

Status
Not open for further replies.

VINSTAR

Not fresh
i write a C program to perform the functions of a calculator,
as this

#include<stdio.h>
#include<conio.h>
int sum(int,int);
int dif(int,int);
int pro(int,int);
float div(int,int);
void main()
{
int a,b;
char o;
clrscr();
printf("enter the numbers ");
scanf("%d%d",&a,&b);
printf("enter the operator(+,-,*,/)");
scanf("%c",&o);
getchar();

if(o=='+')
printf("sum=%d",sum(a,b));
else if(o=='-')
printf("difference=%d",dif(a,b));
else if(o=='*')
printf("product=%d",pro(a,b));
else if(o=='/')
printf("%d/%d=%f",a,b,div(a,b));
else
printf("ERROR!!!");
getch();
}
int sum(int a,int b)
{
int r;
r=a+b;
return(r);
}
int dif(int a,int b)
{
int r;
r=a-b;
return(r);
}
int pro(int a,int b)
{
int r;
r=a*b;
return(r);
}
float div(int a,int b)
{
float r;
r=(float)a/b;
return(r);
}


its not working. There is no error when compile.
i cannot input the operator(+,_,*,/).
but when i change the order of the program, ie
input the operator first and then input the numbers
then the program is working fine. like this,,

#include<stdio.h>
#include<conio.h>
int sum(int,int);
int dif(int,int);
int pro(int,int);
float div(int,int);
void main()
{
int a,b;
char o;
clrscr();
printf("enter the operator(+,-,*,/)");
scanf("%c",&o);
getchar();
printf("enter the numbers ");
scanf("%d%d",&a,&b);

if(o=='+')
printf("sum=%d",sum(a,b));
else if(o=='-')
printf("difference=%d",dif(a,b));
else if(o=='*')
printf("product=%d",pro(a,b));
else if(o=='/')
printf("%d/%d=%9.2f",a,b,div(a,b));
else
printf("ERROR!!!");
getch();
}
int sum(int a,int b)
{
int r;
r=a+b;
return(r);
}
int dif(int a,int b)
{
int r;
r=a-b;
return(r);
}
int pro(int a,int b)
{
int r;
r=a*b;
return(r);
}
float div(int a,int b)
{
float r;
r=(float)a/b;
return(r);
}


Why is it happening so? i am using Turbo C++ 3.0
in windows xp sp2. Anybody PLS HLP ME.
 

webgenius

Ambassador of Buzz
use this statement after reading the numbers:
fflush(stdin);

include the header stdlib.h for this to work. Compile the program again n let me know.
 

fun2sh

Pawned!... Beyond GODLIKE
yep use
Code:
fflush(stdin);
after the first scanf statement
or else the scanf reads some garbage values from n stores it in O so u gettin that error!
 
Last edited:

ayush_chh

Ambassador of Buzz
yes there is no need to use getchar() but using scanf() for accepting characters is not recommended......the problem with your program is that buffer is blocked....so u may use fflush(stdin); before scanf() for clearing input buffer....or u can use this code
Code:
printf("enter the numbers ");
scanf("%d%d",&a,&b);
printf("enter the operator(+,-,*,/)");
o=getche();
getch();
if(o=='+')
 
OP
VINSTAR

VINSTAR

Not fresh
THANKS TO ALL
Anybody pls help me to get the ebook copy of "LET US C" by yeshwant kanitkar
 
Status
Not open for further replies.
Top Bottom