|
Author |
Topic: accessing variables (Read 253 times) |
|
lim
|
accessing variables
« on: Jun 30th, 2004, 2:49pm » |
|
Please, how could I get the frst (or second) number of a variable? I mean for istance: int s = second(); // Values 34 (example) I want to get the two number: 3 (first) or 4 (second) Thanks in advance
|
|
|
|
TomC
|
Re: accessing variables
« Reply #1 on: Jun 30th, 2004, 3:49pm » |
|
OK, I was slightly confused by your use of the second() function to get an example number, but I think I know what you mean now. With integers, it's pretty easy. As with everything, there's more than one way to do it though. Here's one way. Code: int example = 34; int tens = example / 10; // should be right for 0 <= example <= 99 int units = example % 10; |
| If you want to do this for a greater range of numbers, you need more use of the modulus operator, to make sure you don't say that e.g. the second digit of '134' is '13'. For example: Code: int example = 12345; int tenthousands = (example / 10000) % 10; int thousands = (example / 1000) % 10; int hundreds = (example / 100) % 10; int tens = (example / 10) % 10; int units = example % 10; println(example + " has:"); println(tenthousands + " tenthousands"); println(thousands + " thousands"); println(hundreds + " hundreds"); println(tens + " tens"); println(units + " units"); |
| A more general function would go through the number and then return an array. That's an exercise for the reader
|
« Last Edit: Jun 30th, 2004, 4:13pm by TomC » |
|
|
|
|
lim
|
Re: accessing variables
« Reply #2 on: Jul 1st, 2004, 10:42am » |
|
Hi TomC, thanks for youur quick reply. I've tried the modulo way, but I can't understand how to get both the number. I 'mean... int example = 34; int units = example % 10; it gets me only the second number (in this case: 4). But how to get the first? (in this case number 3). I need to access to both the numbers. Thanks again.
|
|
|
|
TomC
|
Re: accessing variables
« Reply #3 on: Jul 1st, 2004, 11:52am » |
|
As I showed in the example above, to get the first digit of a 2 digit number, you need to divide by 10. Integer division will throw away the units when you divide by 10.
|
|
|
|
|