Ignore negative number
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5

Thread: Ignore negative number

Hybrid View

  1. #1
    Join Date
    May 2013
    Posts
    2

    Ignore negative number

    Hey I need help with ignoring negative numbers when I am trying to add up only positive numbers.


    SAMPLE:
    if (num>=0) {
    sum= sum + num;
    }
    else


    how would the else in this case being a negative number not be included in the sum

    THANKS!

  2. #2
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Posts
    12,121

    Re: Ignore negative number

    You don't need an else. The if by itself is enough.

  3. #3
    Join Date
    May 2013
    Posts
    2

    Re: Ignore negative number

    True however it would still take an inputted negative number how do i prevent that from happening.

  4. #4
    Join Date
    Jul 2005
    Location
    Netherlands
    Posts
    2,014

    Re: Ignore negative number

    Quote Originally Posted by cplusplusnoob View Post
    True however it would still take an inputted negative number how do i prevent that from happening.
    The code snippet you posted does not "take a number". You'll have to show the code you are talking about, otherwise we can only guess.
    Cheers, D Drmmr

    Please put [code][/code] tags around your code to preserve indentation and make it more readable.

    As long as man ascribes to himself what is merely a posibility, he will not work for the attainment of it. - P. D. Ouspensky

  5. #5
    Join Date
    Dec 2012
    Location
    England
    Posts
    2,546

    Re: Ignore negative number

    Code:
    if (num > 0) {
        sum += num;
    }
    For efficiency, the test should be greater than, because if num is 0, adding 0 to sum leaves sum unchanged.
    All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center