weird value in operate variable, please help newbie

D

Dux

Hoping someone can help me debug this code, I get strange values in
operate variable, as far as I can see that is problem, in help welcomed.


#include <stdio.h>

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

printf("Enter a number\n");
scanf("%f",&num1);
printf("Enter an operator\n");
scanf("%c",&operate);
printf("Enter number 2\n");
scanf("%f",&num2);
printf("variables = %f, %c, %f\n",num1,operate,num2);
switch(operate)
{ case '+': result = num1+num2;
printf("num1 + num2 = %.2f\n",result);
break;
case '-': result = num1-num2;
printf("num1-num2= %.2f\n",result);
break;
case '*': result = num1*num2;
printf("num1*num2= %.2f\n",result);
break;
case '/': result = num1/num2;
printf("num1/num2= %.2f\n",result);
break;
}
return 0;
}
 
M

Mike Wahler

Dux said:
Hoping someone can help me debug this code, I get strange values in
operate variable, as far as I can see that is problem, in help welcomed.


#include <stdio.h>

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

printf("Enter a number\n");
scanf("%f",&num1);
getchar();

printf("Enter an operator\n");
scanf("%c",&operate);
getchar();

printf("Enter number 2\n");
scanf("%f",&num2);
getchar();

printf("variables = %f, %c, %f\n",num1,operate,num2);
switch(operate)
{ case '+': result = num1+num2;
printf("num1 + num2 = %.2f\n",result);
break;
case '-': result = num1-num2;
printf("num1-num2= %.2f\n",result);
break;
case '*': result = num1*num2;
printf("num1*num2= %.2f\n",result);
break;
case '/': result = num1/num2;
printf("num1/num2= %.2f\n",result);
break;
}
return 0;
}

What I've added above is only a "quick hack",
yor program will still not handle invalid input
correctly.

Study the documentation of 'scanf()' to learn
its behavior when the input is invalid. Then
consider desiging more robust input methods.
Hints: 'fgets()', 'strtod()'.

-Mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top