-
May 15th, 2013, 08:14 PM
#1
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!
-
May 15th, 2013, 08:39 PM
#2
Re: Ignore negative number
You don't need an else. The if by itself is enough.
-
May 15th, 2013, 09:46 PM
#3
Re: Ignore negative number
True however it would still take an inputted negative number how do i prevent that from happening.
-
May 16th, 2013, 01:47 AM
#4
Re: Ignore negative number
Originally Posted by cplusplusnoob
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
-
May 16th, 2013, 06:48 AM
#5
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|