add up all numbers?

Discussion in 'Mac Programming' started by chris200x9, Nov 12, 2007.

  1. macrumors 6502a

    #1
    the output of this is just th same number, why wouldnt it be the total of all the numbers that make it up?


    Code:
    #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;
    }
    
     
  2. macrumors regular

    #2
    Code:
    #include <iostream>
    using namespace std;
    
    int main () {
    int num;
    
      cout << "input a number" << endl;
      cin >> num;
      cout << endl;
      while (num < 0 )
      {
      [B]num1[/B]= num;
      num = num + num;
      
      num--;
      }
      cout << num;
        return 0;
    }
    
    I would check out your variable names in your while loop. Your num1 is doing nothing.
     
  3. macrumors 6502a

    #3
    If you consider this logic,

    Code:
      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
     
  4. macrumors 6502a

    #4
    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
     
  5. macrumors 601

    HiRez

    #5
    Probably 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.
     
  6. macrumors 6502a

    #6
    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:
    Code:
    while (num [color=red]>[/color] 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.
    Code:
    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
     

Share This Page