1

I am trying to write a program that is able to read two real numbers followed by a character which is inputted by the user. Then the program will evaluate the two numbers by the character. The character can be any of the ones that I have listed below:
1. + (addition)
2. - (subtraction)
3. * (multiplication)
4. / (division)
5. % (remainder)

Below I have posted the code that I have written just to check if the values printed out are correct:

#include<stdio.h>

int main(){
    float a,b,add,subtract,division,multiply,remainder;
    char op;

    printf("Enter two real numbers followed by one these characters:+, -, *, /, or % : ");
    scanf("%f%f %c",&a,&b,&op);
    printf("%.1f %c %.1f\n",a,op,b);

    if (op=='+'){
        add =  a + b;
        printf("%f",add);
    }
    else if (op=='-'){
        subtract=a-b;
        printf("%f",subtract);
    }
    else if (op=='/'){
        division=a/b;
        printf("%f",division);
    }
    else if (op=='*'){
        multiply =a*b;
        printf("%f",multiply);
    }
    else if (op=='%'){
        remainder=a%b;
        printf("%f",remainder);
    }
    else{
        printf("invalid symbol");
    }
    return 0; 
}

Can anyone tell me why I am getting a run time error?

code_dredd
  • 5,915
  • 1
  • 25
  • 53
Drew
  • 73
  • 2
  • 9
  • 1
    Just a quick note that you should post the output of your program as text instead of a picture if possible. The font in the picture is fairly small and not as easy to read. – code_dredd May 30 '16 at 00:37
  • Also, you say you want to read *real* numbers, but you're using variables of type `int` instead of `float` – code_dredd May 30 '16 at 00:38
  • `printf("%d %c %d",a,b,op);` -- The behavior is undefined, as the variables do not match the types described in the format string. Next time, use `std::cin` and `std::cout`, not `scanf` and `printf`. – PaulMcKenzie May 30 '16 at 00:40
  • 1
    Your edits have basically transformed your original question into something completely different. Please post a separate question instead of invalidating the answers that were addressing the original question in the first place. Also, in the follow up question, remember to add information on how you're using the program, the error it produces, and its output, etc. We can't guess. – code_dredd May 30 '16 at 01:29

2 Answers2

3

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.

  1. The command-line input for your program has to be properly converted to float types, but it converts them to ints. Your scanf should use "%f %f %c" instead to take real numbers instead of integer numbers;
  2. 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)
  3. 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
code_dredd
  • 5,915
  • 1
  • 25
  • 53
  • @Drew: Note that if you're trying to create a program that can evaluate *any* postfix expression (e.g. `2 2 + 8 * 6 + /`), then you'll really need to look at using a stack or something more elaborate. – code_dredd May 30 '16 at 01:26
  • what about finding remainder? – Drew May 30 '16 at 01:32
  • @Drew: Remainder is only applicable to integer division. Change all the types and text to be about `int` types instead if you want to add it. See [this answer](http://stackoverflow.com/a/6103040/4594973) – code_dredd May 30 '16 at 01:34
  • @Drew: I updated the code a bit to cover the remainder without you having to turn everything into an `int`. The approach being used, where you see `(int)a`, is called *type casting*. Note that the result there is going to be more of an approximation due to the casting ignoring the fractional parts. – code_dredd May 30 '16 at 03:35
1

The problem is in the way you're printing it. You're trying to print a number as a char and a char as a number:

printf("%d %c %d",a,b,op);

I think you meant:

printf("%d %d %c",a,b,op);

So it was just printing the ASCII value of b, which will give you a funny character as you have there.

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
Omar Shehata
  • 1,054
  • 14
  • 18
  • This is unlikely to be enough. The OP claims to want real numbers, but the variables being used to hold them are of type `int`, which is incorrect. The code should be using `float` types for that and also print them accordingly (i.e. `%f`). – code_dredd May 30 '16 at 00:41
  • Is there a way around it? I wanted to print it out because later on I'd like to evaluate that line. Example : user enters " 2 2 +" then evaluate it as "2+2" and print total – Drew May 30 '16 at 00:41
  • @Drew: You should probably start with something simpler. If you want to evaluate expressions using postfix notation, you'll need to work with a stack and other data structures, which I get the impression you're not familiar with. – code_dredd May 30 '16 at 00:43
  • 1
    @Drew, you can switch `op` and `b` in the call to `printf`. Use `printf("%d %c %d",a, op, b);` – R Sahu May 30 '16 at 00:44
  • @ray yeah I'm trying to learn this by myself if you can direct me to any resources that would be great. – Drew May 30 '16 at 00:45
  • @RSahu: That wouldn't help in evaluating the expression `2+2`, it'd only print it that way. – code_dredd May 30 '16 at 00:47
  • @Drew: You probably need to find a book to learn the fundamentals, maybe using a language that might be easier to learn than C (e.g. Python). Just a suggestion. – code_dredd May 30 '16 at 00:49
  • @ray: Why do you say "You should probably start with something simpler", and then suggest doing something more complex? The OP doesn't need a stack or any other data structures to do what he describes. He just needs a switch on `op`. – Benjamin Lindley May 30 '16 at 00:50
  • @ray when using %f, if i rewrite it as %.1f does that show up to one decimal place? – Drew May 30 '16 at 00:50
  • @ray, of course. His first milestone seems to be to be able to print the input data in `2+2` form. Evaluation is the next step. – R Sahu May 30 '16 at 00:51
  • @BenjaminLindley: He OP is also trying to *evaluate* the expression and get the total (i.e. `4`). His code is simply handling characters and is not even converting the `'2'`s that he feeds in the prompt, which come in as type `char`, into actual numbers. You're only focusing on printing order, which is trivial and does not help with what's left. I'm not suggesting anything more complex than what's actually needed. – code_dredd May 30 '16 at 00:53
  • @ray: Yes, it is converting the 2. scanf does that. All he needs to do to evaluate the expression is, like I said, a switch (or if/else series) on `op`, and then do the appropriate operation on `a` and `b`. – Benjamin Lindley May 30 '16 at 00:55
  • @BenjaminLindley: You're right. What I had in mind there, which I wasn't too clear about, was that the conversion is still incorrect as the text claims to want real numbers, but he's using integers instead, which is an issue. My suggestion of the stack was because I ended up thinking the OP wanted a general solution that could evaluate any postfix expression. That might not be what the OP is after, but it didn't seem clear cut. – code_dredd May 30 '16 at 01:01