CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums
Results 1 to 2 of 2

Thread: I'm bad help me why doesn't this work

  1. #1
    Join Date
    Nov 2018

    I'm bad help me why doesn't this work

    #include <iostream>
    using namespace std;
    int main() { 
        int x;
        int a, b;
        cout << "welcome to the calculator" << endl;
        cout << "enter 1 for division, 2 for multiplication, 3 for addition and 4 for subtraction" << endl;
        cin >> x;
        int sum;
        if (x == 1) {
            sum = a / b;
        if (x == 2) {
            sum = a * b;
        if (x == 3) {
            sum = a + b;
        if (x == 4) {
            sum = a - b;
        cout << "enter a number" << endl;
        cin >> a;
        cout << "one more please" << endl;
        cin >> b;
        cout << "and your answer is!" << endl; 
        cout << sum;
        return 0;
    It just says - 37 or 0. I want it to be able to calculate stuff
    Last edited by 2kaud; November 19th, 2018 at 10:13 AM. Reason: Added code tags

  2. #2
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012

    Re: I'm bad help me why doesn't this work

    When posting code, please use code tags so that the code is readable. Go Advanced, select the formatted code and click '#'.

    You first define the variables a and b without specifying their values. You then use them in calculations to produce a value for sum. Then after the calculations you ask the user to input the values for a and b. However the entered values are not used as the input comes after they are used. You need to have the cout/cin statements referring to a and b before these variables are used in the calculation for sum.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++17 Compiler: Microsoft VS2019 (16.6.3)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Windows Mobile Development Center

Click Here to Expand Forum to Full Width

On-Demand Webinars (sponsored)