C: how to break apart a multi digit number into se

2020-01-29 07:15发布

Say I have a multi-digit integer in C. I want to break it up into single-digit integers.

123 would turn into 1, 2, and 3.

How can I do this, especially if I don't know how many digits the integer has?

11条回答
做个烂人
2楼-- · 2020-01-29 07:57
//Based on Tony's answer
#include <stdio.h> 
int nthdig(int n, int k){
    while(n--)
        k/=10;
    return k%10;
}

int main() {
    int numberToSplit = 987;
    printf("Hundreds = %i\n",nthdig(2, numberToSplit));
    printf("Tens     = %i\n",nthdig(1, numberToSplit));
    printf("Units    = %i\n",nthdig(0, numberToSplit));
}

This results in the following printout:

Hundreds = 9

Tens = 8

Units = 7

查看更多
一纸荒年 Trace。
3楼-- · 2020-01-29 08:00

As a hint, getting the nth digit in the number is pretty easy; divide by 10 n times, then mod 10, or in C:

int nthdig(int n, int k){
     while(n--)
         k/=10;
     return k%10;
}
查看更多
放我归山
4楼-- · 2020-01-29 08:02

First, count the digits:

unsigned int count(unsigned int i) {
 unsigned int ret=1;
 while (i/=10) ret++;
 return ret;
}

Then, you can store them in an array:

unsigned int num=123; //for example
unsigned int dig=count(num);
char arr[dig];
while (dig--) {
 arr[dig]=num%10;
 num/=10;
}
查看更多
叛逆
5楼-- · 2020-01-29 08:14

I think below piece of code will help....

temp = num;
while(temp)
{
    temp=temp/10;
    factor = factor*10;
}

printf("\n%d\n", factor);
printf("Each digits of given number are:\n");

while(factor>1)
{
    factor = factor/10;
    printf("%d\t",num/factor);
    i++;
    num = num % factor;
}
查看更多
做自己的国王
6楼-- · 2020-01-29 08:15

You can use %10, which means the remainder if the number after you divided it. So 123 % 10 is 3, because the remainder is 3, substract the 3 from 123, then it is 120, then divide 120 with 10 which is 12. And do the same process.

查看更多
登录 后发表回答