PDA

View Full Version : add up all numbers?

chris200x9
Nov 12, 2007, 06:40 PM
the output of this is just th same number, why wouldnt it be the total of all the numbers that make it up?

#include <iostream>
using namespace std;

int main () {
int num;

cout << "input a number" << endl;
cin >> num;
cout << endl;
while (num < 0 )
{
num1= num;
num = num + num;

num--;
}
cout << num;
return 0;
}

CaptainZap
Nov 12, 2007, 07:07 PM
#include <iostream>
using namespace std;

int main () {
int num;

cout << "input a number" << endl;
cin >> num;
cout << endl;
while (num < 0 )
{
num1= num;
num = num + num;

num--;
}
cout << num;
return 0;
}

toddburch
Nov 12, 2007, 07:46 PM
If you consider this logic,

while (num < 0 )
{
num1= num;
num = num + num;

num--;
}

Let's run an example number through. Let's pick 4.

while (4 < 0) { .... }

Humm. What's wrong with that picture?

Todd

chris200x9
Nov 12, 2007, 08:21 PM
If you consider this logic,

while (num < 0 )
{
num1= num;
num = num + num;

num--;
}

Let's run an example number through. Let's pick 4.

while (4 < 0) { .... }

Humm. What's wrong with that picture?

Todd

omfg I feel more retarded than those people in that one current event article on here :)

I dont get why it just outputs the negative limit of integers

HiRez
Nov 13, 2007, 02:18 AM
omfg I feel more retarded than those people in that one current event article on here :)

I dont get why it just outputs the negative limit of integersProbably because it loops throught that many times, decrementing num by 1 each time until it reaches the limit. At that point I'm not sure what happens. I suppose it either wraps around, or zeroes out all the bits thereby making num >= 0 and terminating the loop.

toddburch
Nov 13, 2007, 07:07 AM
I don't know what you did to change the logic since my last post, but if you just flipped the relational operator to this:

while (num > 0 )
{
num1= num;
num = num + num;

num--;
}

then that might not be getting you to where you want to go either.

Let's look at the logic again. We'll pick 4 again.

while (4 > 0 )
{
//num1= num; not sure what this line is supposed to do???
num = 4 + 4 ; // double num

num--; // subtract one - it's now 7
}

Every iteration will double the number and then subtract 1. When num, a 4 byte integer, reaches one more than X'7FFFFFFF' (2gb), it will go negative, since the sign bit will be on, and the WHILE loop will quit.

What is your loop supposed to be doing?

Todd