mr_Alex_Nok_
mr_Alex_Nok_

Reputation: 62

throwing away tens & hundreds columns of an int in C

I want to test an integer value for its units column value only, I don't care about the tens or hundreds columns. The int value is a countdown timer

So when the units column is 0 to 4 I want the screen to display something, when the units is 5 to 9 I want the screen to display something else. I want to basically isolate the units column value

Can't think of a quick and dirty way of doing this without dividing by 100 and subtracting the number of 100s then doing the same with the number of 10s. Is there a simpler way of shifting and testing for 0 to 4 or 5 to 9 in the units column

So far I am trying:

int zero_count_units = a_zero_count - (((a_zero_count / 100) * 100) + ((a_zero_count / 10) * 10));

if( (zero_count_units >= 0) && (zero_count_units < 5) )     // 0-4 units column
{
}
else if( (zero_count_units >= 5) && (zero_count_units <= 9) )   // 5-9 units column
{
}

My brain isn't working particularly well this morning! Any advice appreciated Many thanks

Upvotes: 1

Views: 216

Answers (2)

Utkan Gezer
Utkan Gezer

Reputation: 3069

int yourNumber = 324687              /* whatever your number is */
int temp = yourNumber;
                                     /* i is to track which digit you're at */
for ( int i = 1; temp != 0; i++ ) {  /* ( temp != 0 ) is the same as ( temp ) alone */
    if ( i > 3 ) {
        if ( temp % 10 < 5 ) {       /* the current last digit of temp */
            /* display something */
        }
        else {
            /* display something else */
        }
    }
    temp /= 10;                      /* this cuts off the last digit */
}

I think this would do what you are trying to ask for. You said you don't want tens (i == 2), hundreds (i == 3), I assumed you wouldn't want ones (i == 1) as well, but you may play around with that as you wish.

Upvotes: 0

unwind
unwind

Reputation: 399959

You need to use the % (modulo) operator.

The expression n % m for two integers n and m evaluates to the remainder after n is divided by m.

In your case m would be 10, since you're interested in the remainder after division by ten:

const int zero_count_units = a_zero_count % 10;

Upvotes: 5

Related Questions