CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  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
    Location
    Florida
    Posts
    12,635

    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,042

    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
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    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. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured