How to split up a two-digit number in C

2019-07-11 18:41发布

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?

标签: c decimal
3条回答
太酷不给撩
2楼-- · 2019-07-11 19:14

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楼-- · 2019-07-11 19:21
2 == 23 / 10
3 == 23 - (23 / 10) * 10
查看更多
贪生不怕死
4楼-- · 2019-07-11 19:38

what about

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

查看更多
登录 后发表回答