Thread: How can i convert negative number to positive number ?

  1. #1
    Registered User
    Join Date
    Mar 2004
    Posts
    41

    How can i convert negative number to positive number ?

    How can i make in such a way that the negative is ignored before adding up the number ??

    Eg: I want the following the code to print out 13 instead of -1.

    Code:
       
    double hello[]={-1,2,4,-6};
    
    for(i=0; i<=3; i++)
    {
         xxx = xxx + hello[i];
    }
    
    printf("%f",xxx);

  2. #2
    Registered User
    Join Date
    Apr 2004
    Posts
    11
    Code:
    double hello[]={-1,2,4,-6};
    
    for(i=0; i<=3; i++)
    {
         if(hello[i] < 0)
             xxx -= hello[i];        /*  ex: x = x - (-1) */
         else
             xxx += hello[i];       /* ex: x = x + 2 */
    }
    
    printf("%f",xxx);

  3. #3
    Registered User
    Join Date
    May 2004
    Posts
    127
    You can use fabs from <math.h>.
    Code:
    #include <stdio.h>
    #include <math.h>
    
    int main(void)
    {
      double hello[]={-1,2,4,-6};
      double xxx = 0;
      int i;
    
      for(i=0; i<=3; i++)
      {
        xxx = xxx + fabs(hello[i]);
      }
    
      printf("%f",xxx);
    
      return 0;
    }
    Also note that your loop is not idiomatic. Most readers will see any deviation from the customary "for (i = 0; i < n; i++)" as a probable error. Your loop is correct, but would be better as "for (i=0; i<4; i++)".

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Read until negative number
    By m_user in forum C Programming
    Replies: 10
    Last Post: 04-03-2009, 06:38 AM
  2. convert 32 bit number to array of digits
    By droseman in forum C Programming
    Replies: 11
    Last Post: 02-18-2009, 09:37 AM
  3. xor linked list
    By adramalech in forum C Programming
    Replies: 23
    Last Post: 10-14-2008, 10:13 AM
  4. Nim Trainer
    By guesst in forum Game Programming
    Replies: 3
    Last Post: 05-04-2008, 04:11 PM
  5. Array of boolean
    By DMaxJ in forum C++ Programming
    Replies: 11
    Last Post: 10-25-2001, 11:45 PM