Please help debug simple tutorial code

I keep getting a result of 2, but what I want is the sum of the two numbers input by the user.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
  #include <iostream>

using namespace std;

//This is a basic hello world program and basic calculator combined
/* This is
 * A multi line
 * comment
 */

void endmessage()
{
    cout << "Goodbye World" << endl;
}
//the int main will be the first part of code that the computer reads
int main()
{
    //this section declared variables so they can later be called upon
    //They are given initial values to help with debugging
    int x = 1;
    int y = 1;
    int total = x + y;

    //This will prompt the user to type in 2 numbers, then the program will return the sum of the numbers
    cout << "Hello World \n\n";
    cout << "Type in a number...\n";
    cin >> x;
    cout << "\nType in another number...\n";
    cin >> y;
    cout << "\nYour total is " << total << "\n\n";
    endmessage();

    return 0;
}
20
21
22
int x = 1;
int y = 1;
int total = x + y; // Sets total to 2 (1 + 1) 
total gets set to the sum of x and y at the time that that line is executed.
Which is 2.

The line int total = x + y; doesn't "bind" the formula x + y to the variable total.
(Remember, total is just an int...so it can only hold integer values, not algebraic formulas.)
Thanks. So how would I get the sum of what the user puts in to become a variable that could be used later?

What I mean is, how can I make it so "total" is variable what changes depending on the sum of x and y
Last edited on
Initialize total after you input values for x and y, not before.

So basically, move line 22 to between lines 29 and 30.
Thanks! Perfect
Registered users can post here. Sign in or register to post.