NOTE: The OP significantly altered the initial question after it had been answered, which is what this post was focusing on, so the answer below may look completely off-target by now.
If anyone can explain why I see different values that would be greatly appreciated.
There're multiple issues with your code.
- The command-line input for your program has to be properly converted to
float
types, but it converts them to int
s. Your scanf
should use "%f %f %c"
instead to take real numbers instead of integer numbers;
- IIRC from your previous picture, your actual inputs to the program looked like this:
2 2 +
, but your scanf
says "%d%d %c"
(notice the missing space in your format string vs your extra space in your input)
- Your
printf
function call needs the arguments swapped to say printf("%f %c %f",a, op, b);
(notice the format string using "%f"
and the inversion of op
and b
variables)
The 1st point is based on the printed text for the user, requesting "real" numbers.
The 2nd and 3rd points are the culprits, because when you enter 2 2 +
on the prompt, your variables look are a = 2
, b = 2
, and op = 43
, which is the numeric value of the '+'
character.
When you then print it, you end up interpreting the '+'
char as if it were an integer and you get 43
instead.
A fixed version of your program is below:
#include<stdio.h>
int main(){
float a, b, result;
char op;
printf("%s", "Enter two real numbers followed an operator (+, -, *, /, %): ");
scanf("%f %f %c", &a, &b, &op);
switch(op) {
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
/* make sure b != 0 */
result = a / b;
break;
case '%':
/* make sure b != 0 */
/* we type-cast to int because modulus is not defined for floats */
result = (float)((int)a % (int)b);
break;
default:
printf("%s\n", "Unknown operation");
break;
}
printf("%f %c %f = %f",a, op, b, result);
return 0;
}
Its usage and output:
➜ /tmp ./test
Enter two real numbers followed an operator (+, -, *, /, %): 5 5 +
5.000000 + 5.000000 = 10.000000
➜ /tmp ./test
Enter two real numbers followed an operator (+, -, *, /, %): 5 5 *
5.000000 * 5.000000 = 25.000000%
➜ /tmp ./test
Enter two real numbers followed an operator (+, -, *, /, %): 5 5 /
5.000000 / 5.000000 = 1.000000%
➜ /tmp ./test
Enter two real numbers followed an operator (+, -, *, /, %): 10 5 %
10.000000 % 5.000000 = 0.000000%
➜ /tmp ./test
Enter two real numbers followed an operator (+, -, *, /, %): 5 10 %
5.000000 % 10.000000 = 5.000000%
➜ /tmp ./test
Enter two real numbers followed an operator (+, -, *, /, %): 8 5 -
8.000000 - 5.000000 = 3.000000