How to split up a two-digit number in C

随声附和 提交于 2019-12-11 02:29:09

问题


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?



来源:https://stackoverflow.com/questions/5275672/how-to-split-up-a-two-digit-number-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!