How to split up a two-digit number in C

2019-07-11 19:12发布

问题:

Let's say I have a number like 21 and I want to split it up so that I get the numbers 2 and 1.

To get 1, I could do 1 mod 10. So basically, the last digit can be found out by using mod 10.

To get 2, I could do (21 - (1 mod 10))/10.

The above techniques will work with any 2-digit number.

However, let me add a further constraint, that mod can only be used with powers of 2. Then the above method can't be used.

What can be done then?

回答1:

2 == 23 / 10
3 == 23 - (23 / 10) * 10


回答2:

To get 2 you can just do

int x = 23 / 10;

remember that integer division drops the fractional portion (as it can't be represented in an integer).

Modulus division (and regular division) can be used for any power, not just powers of two. Also a power of two is not the same thing as a two digit number.

To split up a three digit number

int first = 234/100;
int second = (234/10)-first*10;
int third = (234/1)-first*100-second*10;

with a little work, it could also look like

int processed = 0;
int first = 234/100-processed;
processed = processed + first;
processed = processed * 10;
int second = 234/10-processed;
processed = processed + second;
processed = processed * 10;
... and so on ...

If you put a little more into it, you can write it up as a loop quite easily.



回答3:

what about

x%10 for the second digit and x/10 for the first?



标签: c decimal