Thread: Need help with creating a basic calculator for homework

  1. #1
    Registered User
    Join Date
    Nov 2015
    Location
    Serbia, Dimitrovgrad
    Posts
    12

    Need help with creating a basic calculator for homework

    Greetings, my name is Nikola and I am kinda new to the C programming thing.
    Our professor gave us a few exercises, one of them is to create a basic calculator.

    I literally copied everything on the following picture from our book:

    Need help with creating a basic calculator for homework-capture1-jpg

    But for some reason when I compile it & run it I get this:

    Need help with creating a basic calculator for homework-capture-png

    It asks me to enter the 1st & 2nd number, afterwards it should ask me to enter: +, -, * or / but it doesn't and when I press enter after entering the 2nd number this is the outcome. (picture above)

    I'd really appreciate it if someone could lend me a hand & give me a few tips, teach me a trick or two

    Oh, just in case, to avoid confusion:
    Unesite prvi sabirak = Insert the 1st number
    Unesite drugi sabirak = Insert the 2nd number
    Unesite znak zeljene operacije (+, -, *, /) = Insert the symbol for the desired operation (+, -, *, /)
    Rezultat operacije je = Result of operation is

  2. #2
    misoturbutc Hodor's Avatar
    Join Date
    Nov 2013
    Posts
    1,787
    What book is that from? I can see at least 6 errors in that code. (edit: make that at least 7. edit 8)
    Last edited by Hodor; 11-16-2015 at 08:31 AM.

  3. #3
    Registered User
    Join Date
    Nov 2015
    Location
    Serbia, Dimitrovgrad
    Posts
    12
    Oh god, that much??
    Its from a practicum on Serbian, why?

    Anyways, thanks for your reply, can you point the errors out?

  4. #4
    misoturbutc Hodor's Avatar
    Join Date
    Nov 2013
    Posts
    1,787
    Quote Originally Posted by Nikola Zlatanov View Post
    Oh god, that much??
    Its from a practicum on Serbian, why?

    Anyways, thanks for your reply, can you point the errors out?
    Yes, I can.

    But before I do, can you see if you can turn your compiler warnings up higher? Maybe google for "Dev-C++ increase warnings" or something like that (I'm sorry, I've never used Dev-C++ so I don't know how)

  5. #5
    misoturbutc Hodor's Avatar
    Join Date
    Nov 2013
    Posts
    1,787
    Ok, for future reference, don't paste images... post actual C source code like:

    Code:
    [code]
    // Your code here
    [/code]
    Now, to the program. I've typed it in basically as you presented.

    Code:
    #include <stdio.h>
    
    void main()
    {
        //
        int B1, B2;
        double R;
        char O;
        
        //
        printf("Enter the 1st number: ");
        scanf("%d", &B1);
        printf("Enter the 2nd number: ");
        scanf("%d", B2);
        printf("Insert the symbol for the desired operation (+, -, *, /) : ");
        O = getchar();
        
        //
        if (O == '+') {
            R = B1 + B2;
            }
        else if (O == '-') {
            R = B1 - B2;
            }
        else if (O == '*') {
            R = B1 * B2;
            }
        else if (O == '/') {
            R = B1 / B2;
            }
        
        //
        printf("Result of the operation is: %d", R);
        
        system("PAUSE");
        return 0;
    }
    Since this is probably very new to you, your professor has probably omitted error checking code deliberately (for demonstration purposes) so I won't comment on that too much. But in real life you should be checking the return values of scanf() and getchar() (also char O; should be int O; because getchar returns an integer that might be EOF which you should also check for.) But let's skip past all that for now.

    Code:
    #include <stdio.h>
    
    //!!! There are only two valid ways to declare void:
    //!!!    int main(void) and 
    //!!!    int main(int argc, char *argv[])
    //!!! The one you want in this example is int main(void)
    //!!! Note also that there is another problem with void main(void): At the end you have
    //!!!     return 0; but your declaration says that main returns nothing. Leave the return 0
    //!!!     because that is correct, but change how you declare main()
    void main()    //!!! Change this to int main(void)
    {
        //
        int B1, B2;
        double R;
        char O;        //!!! Technically this should be int O; because getchar returns int
        
        //
        printf("Enter the 1st number: ");
        scanf("%d", &B1);
        printf("Enter the 2nd number: ");
        scanf("%d", B2);    ///!!! Does this look similar to the previous scanf()? %d expects you to
                            ///!!!    supply "a pointer to the place to store the result". Don't worry about
                            ///!!!    what & does at the moment I guess (you'll learn later), just note that it should be &B2
        printf("Insert the symbol for the desired operation (+, -, *, /) : ");
        O = getchar();
        ///!!! Some time when you learn more you should check for EOF here. You should also check that you have
        ///!!! actually read a character that is not whitespace (spaces, tabs, end of line characters etc).
        
        
        //
        if (O == '+') {
            R = B1 + B2;
            }
        else if (O == '-') {
            R = B1 - B2;
            }
        else if (O == '*') {
            R = B1 * B2;
            }
        else if (O == '/') {
            R = B1 / B2;    ///!!! R is of type double, but the expression B1 / B2 is of type int, so this
                            ///!!! likely does not do what it's meant to do
            }
        ///!!! what happens if O did not equal any of those characters (+ - * /)? In the next logical line you
        ///!!!    will print the value of R, but R is not initialized.
        
        //
        printf("Result of the operation is: %d", R);    ///!!! %d says to print an integer, but R is a double
        
        system("PAUSE");    ///!!! Don't worry about this for now, but note that it won't work on anything but (probably) Windows
        return 0;    //!!! See my comment before main()    (this line is correct, the declaration of main is not. You can't return a 
                      //!!! value from a function that is declared to return void (i.e. nothing)
    }
    Last edited by Hodor; 11-16-2015 at 09:24 AM. Reason: typo

  6. #6
    misoturbutc Hodor's Avatar
    Join Date
    Nov 2013
    Posts
    1,787
    As something that is more correct, but not great:

    Code:
    #include <stdio.h>
    
    int main(void)    //!! I changed this
    {
        //
        int B1, B2;
        double R;
        int O;        //!! I changed the type to int
        
        //
        printf("Enter the 1st number: ");
        scanf(" %d", &B1);        //!! I inserted a space before the %d to skip whitespace
        printf("Enter the 2nd number: ");
        scanf(" %d", &B2);        //!! I inserted a space before the %d to skip whitespace and changed B2 to &B2
        printf("Insert the symbol for the desired operation (+, -, *, /) : ");
        //!!! You should probably have something here to make sure there is no whitespace before the character (operator)
        O = getchar();
        
        //
        if (O == '+') {
            R = B1 + B2;
            }
        else if (O == '-') {
            R = B1 - B2;
            }
        else if (O == '*') {
            R = B1 * B2;
            }
        else if (O == '/') {
            R = B1 / B2;
            //!!! The above line is tricky to fix without introducing you to new concepts. Let's just say
            //!!!    for now that if B1 is 3 and B2 is 2 then R will be given the value 1 (and not 1.5
            //!!!    because integer divisions will not have the fractional part. The line should probably
            //!!!    be R = (double) B1 / B2;
            }
        else { //!!! I added this
            R = 0;    //!!! At least initialise R to something even though it's wrong
            printf("Invalid operator (the result printed will not be correct)\n");
            }
        //
        printf("Result of the operation is: %f", R);    //!! Changed %d to %f
        
        system("PAUSE");    //!! Sometime in the future you should ponder this line
        return 0;
    }
    I haven't compiled or tested this, but apart from adding error checking I think it's correct for fixing the obvious mistakes. Try it out and let people know (I'm going to sleep). Good luck.

    Edit: If it doesn't work, when you see "Enter the 1st number:" instead of waiting for the other prompts just enter 5 2+ and hit the enter/return key. If that then gives the expected result then I'm sure someone will tell you why
    Last edited by Hodor; 11-16-2015 at 09:50 AM.

  7. #7
    Registered User
    Join Date
    Sep 2004
    Posts
    21
    You will need to read about scanf and getchar functions. Here is what is happening, let's focus on second scanf:
    scanf("%d", &B2);
    Suppose you type 5 and hit the enter key, now scanf takes only the numeric value, in this case, 5 from the input buffer but still the linefeed character (which is when you hit the enter key) is in the input buffer.
    Now what the getchar function does is to check the input buffer and it sees there is data in it, namely the linefeed character it then consumes it and goes on and that's why you don't see it prompting you. Here is one way to prevent this issue, before getchar function make sure the input buffer is cleared by using fflush(stdin);

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by rassul
    Here is one way to prevent this issue, before getchar function make sure the input buffer is cleared by using fflush(stdin);
    This is a bad solution: fflush is only defined for output streams and update streams for which the last operation was output. Therefore, fflush(stdin) results in undefined behaviour.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  9. #9
    Registered User
    Join Date
    Sep 2004
    Posts
    21
    laserlight is right, we should use fflush function for output, therefore instead of using fflush we can clear the input buffer like:
    Code:
    while((O = getchar()) != '\n' && O != EOF);
    and then call getchar function.

  10. #10
    misoturbutc Hodor's Avatar
    Join Date
    Nov 2013
    Posts
    1,787
    Quote Originally Posted by rassul View Post
    laserlight is right, we should use fflush function for output, therefore instead of using fflush we can clear the input buffer like:
    Code:
    while((O = getchar()) != '\n' && O != EOF);
    and then call getchar function.
    That's not great either. That will just "eat" '\n' characters. What about all the other whitespace?

  11. #11
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by Hodor
    That's not great either. That will just "eat" '\n' characters. What about all the other whitespace?
    No, it will read and discard characters until the first newline character is encountered, or until getchar returns EOF.

    That said, O is a terrible variable name: it is so easily mixed up with the integer literal 0 in many fonts. Nikola Zlatanov, I recommend that you use a more descriptive and distinctive variable name, e.g., operation.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  12. #12
    Registered User
    Join Date
    Nov 2015
    Location
    Serbia, Dimitrovgrad
    Posts
    12
    @Hodor & others
    Sorry for using pictures & thank you for your replies & explanation. I bookmarked this page because I have a feeling that I am gonna be returning to re-read everything in the near future again~
    I changed everything like you told me to and it works! Kinda:

    Attachment 14443

    It's kinda messy tho. 0's appear after the result but it's not incorrect I guess. And the "Press any key to continue" is in a bad position, oh well. Thanks a lot.

    @rassul & others
    I tried both, the
    Code:
    fflush(stdin);
    and the

    Code:
    while((O = getchar()) != '\n' && O != EOF);
    code. Using both I achieved the same results (picture above).

    I have a few questions:
    What are "whitespaces" in a few words?
    Why did Hodor change %d to %f? What does the %f do?

    @laserlight
    Thanks for your suggestion, I am gonna do it from now on!

    Again thanks for your help guys I really appreciate it & sorry... I kinda cringe because you literally did part of my homework but thanks for all the explanation!
    Last edited by Nikola Zlatanov; 11-16-2015 at 01:18 PM.

  13. #13
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by Nikola Zlatanov
    Using both I achieved the same results (picture above).
    As a consequence of undefined behaviour, fflush could be implemented such that fflush(stdin) discards whatever is in the standard input buffer, but this is of course not guaranteed.

    Quote Originally Posted by Nikola Zlatanov
    What are "whitespaces" in a few words?
    An umbrella term referring to space (' '), horizontal tab ('\t'), new-line ('\n'), vertical tab ('\v'), and form-feed ('\f').

    Quote Originally Posted by Nikola Zlatanov
    Why did Hodor change %d to %f? What does the %f do?
    For printf, %d is used to print an int. %f is used to print a double. Since R is a double, it is appropriate to use %f rather than %d to print R. Again, consider a more descriptive name like result.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  14. #14
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Dev-c++ 4.9.9.2 is obsolete (has been for about 10 years).
    Aside from the compiler being that old (gcc has moved on a long way since then), the IDE has a number of serious bugs which trash project files.

    Consider this as a near drop-in replacement.
    Dev-C++ download | SourceForge.net
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  15. #15
    Registered User
    Join Date
    Nov 2015
    Location
    Serbia, Dimitrovgrad
    Posts
    12
    Quote Originally Posted by laserlight
    An umbrella term referring to space (' '), horizontal tab ('\t'), new-line ('\n'), vertical tab ('\v'), and form-feed ('\f').


    I managed to fix the "Press any key to continue" out of position bug thanks to this, so happy right now, thanks (was right after all with bookmarking this page!)

    Need help with creating a basic calculator for homework-capture-png

    Quote Originally Posted by laserlight
    For printf, %d is used to print an int. %f is used to print a double. Since R is a double, it is appropriate to use %f rather than %d to print R. Again, consider a more descriptive name likeresult.
    Nobody ever mentioned that to us before, I dunno if the exercises in the practicum are written incorrectly on purpose or not... But oh well, I learned a lot today. Love ya all~

    @Salem
    We have a website for our school & I downloaded the program, as our professor instructed us from it.
    Do you think that I can replace it with your version? It'll be better right?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help with day calculator. (Homework)
    By Foxhound013 in forum C Programming
    Replies: 5
    Last Post: 10-03-2015, 08:46 PM
  2. Basic calculator
    By Khaled in forum C++ Programming
    Replies: 2
    Last Post: 05-22-2011, 08:17 AM
  3. A Basic Calculator.
    By bijan311 in forum C++ Programming
    Replies: 4
    Last Post: 12-26-2009, 01:53 PM
  4. Basic Calculator
    By Surge in forum C Programming
    Replies: 18
    Last Post: 12-02-2006, 10:20 PM
  5. need help with my basic c++ calculator
    By iCouch_Potato in forum C++ Programming
    Replies: 4
    Last Post: 03-24-2004, 06:23 PM

Tags for this Thread