简体   繁体   中英

How can I iterate through each digit in a 3 digit number in C?

Length is always 3, examples:

000
056
999

How can I get the number so I can use the value of the single digit in an array?

Would it be easier to convert to an char , loop through it and convert back to int when needed?

To get the decimal digit at position p of an integer i you would do this:

(i / pow(p, 10)) % 10;

So to loop from the last digit to the first digit, you would do this:

int n = 56; // 056
int digit;    

while(n) {
    digit = n % 10;
    n /= 10;

    // Do something with digit
}

Easy to modify to do it exactly 3 times.

As Austin says, you can easily find answers on Google. But it basically involves mod-by-10, then divide-by-ten. Assuming integers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM