Determining if a number is either a multiple of ten or within a particular set of ranges

后端 未结 13 1442
Happy的楠姐
Happy的楠姐 2021-01-31 07:01

I have a few loops that I need in my program. I can write out the pseudo code, but I\'m not entirely sure how to write them logically.

I need -

if (num is          


        
13条回答
  •  无人及你
    2021-01-31 07:15

    The first one is easy. You just need to apply the modulo operator to your num value:

    if ( ( num % 10 ) == 0)
    

    Since C++ is evaluating every number that is not 0 as true, you could also write:

    if ( ! ( num % 10 ) )  // Does not have a residue when divided by 10
    

    For the second one, I think this is cleaner to understand:

    The pattern repeats every 20, so you can calculate modulo 20. All elements you want will be in a row except the ones that are dividable by 20.

    To get those too, just use num-1 or better num+19 to avoid dealing with negative numbers.

    if ( ( ( num + 19 ) % 20 ) > 9 )
    

    This is assuming the pattern repeats forever, so for 111-120 it would apply again, and so on. Otherwise you need to limit the numbers to 100:

    if ( ( ( ( num + 19 ) % 20 ) > 9 ) && ( num <= 100 ) )
    

提交回复
热议问题