-2

I need to write logic to break down a 4 digit number into individual digits.

On a reply here at SO to a question regarding 3 digits, someone gave the math below:

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

Can someone help me?

Thank you in advance!

2 Answers2

1

Well, using the sample you found, we can quite easily infer a code for you.

The first line says int first = 321/100;, which returns 3 (integer division is the euclidian one). 3 is indeed the first integer in 321 so that's a good thing. However, we have a 4 digit number, let's try replacing 100 with 1000:

int first = 4321/1000;

This does return 4 !

Let's try adapting the rest of your code (plus I put your four digit number in the variable entry).

int entry = 4321;
int first = entry/1000;
int second = entry/100 - first*10;
int third = entry/10 - first*100 - second*10;
int fourth = entry - first*1000 - second*100 - third*10;

second will be entry/100 (43) minus first*10 (40), so we're okay. third is then 432 - 400 - 30 which turns to 2. This also works till fourth.

For more-than-four digits, you may want to use a for-loop and maybe some modulos though.

PatJ
  • 5,996
  • 1
  • 31
  • 37
  • 1
    Thank you very much! My controller does not have modulo in its math functions; it does have rounding. The older, 1990s, controller I am rewriting the code for, does have a modulo function. That is my problem. – Chris in GE Feb 01 '15 at 18:46
  • 1
    You can use the good old formula: x mod y = x - ( x / y * y ). – PatJ Feb 01 '15 at 22:53
0

This snip of code counts the number of digits input from the user then breaks down the digits one by one:

PRINT "Enter value";
INPUT V#
X# = V#
DO
    IF V# < 1 THEN
        EXIT DO
    END IF
    D = D + 1
    V# = INT(V#) / 10
LOOP
PRINT "Digits:"; D
FOR L = D - 1 TO 0 STEP -1
    M = INT(X# / 10 ^ L)
    PRINT M;
    X# = X# - M * 10 ^ L
NEXT
END
eoredson
  • 1,167
  • 2
  • 14
  • 29