equation doesnt add up...

hello everyone...

i wrote a basic program for my C++ class that includes SUMs and while loops.
its fairly self explanatory, but i am not getting the correct SUMs for my outputs.
apparently, i am missing something extremely important somewhere here.
can someone take a look and give me a few hints as to why my outputs are coming out the way they are...

thank you.

note: why i have so much variables here is because my teacher wants it that way. i would use an array to make the program look neater, but i was instructed to keep it as simple and as basic as possible. =)


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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <iostream>
using namespace std;

int main()
{
    int numX;
    int numY;
    int numZ;
    
    int sum1 = numX - numZ;
    int sum2 = numX - numY + numZ;
    int sum3 = numX + numY;
    
    int sum4 = numX + numY + numZ;
    int sum5 = numX;
    int sum6 = numX - numY - numZ;
    
    int sum7 = numX - numY;
    int sum8 = numX + numY - numZ;
    int sum9 = numX + numZ;
    
    int totalA = sum1 + sum2 + sum3;
    int totalB = sum4 + sum5 + sum6;
    int totalC = sum7 + sum8 + sum9;
    int totalD = sum1 + sum4 + sum7;
    int totalE = sum2 + sum5 + sum8;
    int totalF = sum3 + sum6 + sum9;
    
    while (cin)
    {
          
          cout << "Please enter 3 integers separated by spaces: (enter non-digit to quit)" << endl;
          cin >> numX >> numY >> numZ;
          cin.ignore(1000, 10);
          
          cout << "The magic square is:" << endl;
          cout << sum1 << sum2 << sum3 << " = " << totalA << endl;
          cout << sum4 << sum5 << sum6 << " = " << totalB << endl;
          cout << sum7 << sum8 << sum9 << " = " << totalC << endl;
          cout << "---------------" << endl;
          cout << totalD << totalE << totalF << endl;          
          cout << " " << endl;
          cout << " " << endl; 
   
    }
    
cin.get();    
return 0;
}

In the bit above your while loop all you're doing is adding together uninitialized variables, hence why you're receiving garbage values. You need to move your totals inside your loop after you have read in the values of numX, numY and numZ. You might want to check your output once the sums have been performed too. If the values of sum1, sum2 and sum3 are 3, 4 and 5 respectively, you will get this output from line 37:

345 = 12

Which I'm guessing is not what you want.

Remember that your code will run from top to bottom, and if things aren't in the right order, you won't get the results you want.
Last edited on
HEY thanks a bunch. totally helped me out. =)
Topic archived. No new replies allowed.