我如何可以通过在C 3位数每个数字重复? [英] How can I iterate through each digit in a 3 digit number in C?

查看:105
本文介绍了我如何可以通过在C 3位数每个数字重复?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

长度总是3,例子:

000
056
999

如何能得到一些这样我就可以在阵列中使用单一数字的值?

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

难道是比较容易通过它转换为字符,循环,转换回 INT 在需要的时候?

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

推荐答案

要获得在一个整数我的位置 P 十进制数你可以这样做:

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
}

易于修改做准确的3倍。

Easy to modify to do it exactly 3 times.

这篇关于我如何可以通过在C 3位数每个数字重复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆