Hey guys, I've been working on this for the past weekend between work. I know this is extremely simple and I mean extremely simple, but I'm missing something here. What I'm not understanding is why this is adding 2 to the sum. For instance, I will calculate 12 five times, but the result is 62 when it needs to be obviously 60. If anyone could help me out with a fresh pair of eyes, it would be great. I'm still completely new to C++, so this is driving me crazy haha!
what I would suggest is for lines 7-9 make it int item, count, sum; // only have to declare the variable type once
line 16: sum = item += sum; to something like sum += item; // which means sum = sum + item;
and on line 17 instead of count += 1; you could do count++; // to increment by one
and system("pause") is bad to use unless its just for a small test or something you don't really care about.
I actually use system("pause") to test the programs. Otherwise the program exits and I can't see the result.
I see the shorthand that I need to start using instead of repeating int, but the rest of what you wrote didn't exactly solve the problem. It's still adding 2 to the result.
okay let me try coding up an example myself. and You could also use other things to pause but if its just for testing that should be fine there is article somewhere on this site I think by disch that explains it but I forgot where it was. I'll post up some code in a few minutes.
int main()
{
int item, count = 0, sum = 0;
while (count < 5)
{
cout << "Enter data item: ";
cin >> item;
sum += item;
count++;
}
cout << count << " data items were added " << endl;
cout << "Their sum is " << sum << endl;
}
#include <iostream>
usingnamespace std;
int main()
{
int item;
int count = 0;
int sum = 0;
while(count < 5)
{
cout << "Enter data item: ";
cin >> item;
sum += item;
count++;
}
cout << count << " data items were addede; " << endl;
cout << "Their sum is: " << sum << endl;
return 0;
}
Thanks guys. I have no idea why I'm getting 62. I figured I had everything typed out right. When you saw my sum = sum += item, I was experimenting with it and seeing if it would change the result. Of course it didn't.
I appreciate the help. It was stumping me for the longest time. Thanks again.