如何在C中迭代3位数中的每个数字?

时间:2022-06-29 23:58:41

Length is always 3, examples:

长度总是3个例子:

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?

是否更容易转换为一个字符,循环它,并转换回int当需要时?

2 个解决方案

#1


6  

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

要得到整数i在p处的小数你可以这样做:

(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.

很容易修改,准确地做了3次。

#2


-3  

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

正如奥斯汀所说,你可以在谷歌上轻松找到答案。但它主要涉及到的是-by-10,然后是-by-10。假设整数。

#1


6  

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

要得到整数i在p处的小数你可以这样做:

(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.

很容易修改,准确地做了3次。

#2


-3  

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

正如奥斯汀所说,你可以在谷歌上轻松找到答案。但它主要涉及到的是-by-10,然后是-by-10。假设整数。