Hello, Ive been trying to get the digits that exist in an integer, but I do not really know how to do that. SUppose I have:
How can I put the different digits into separate variables? For example 1, 0, 0PHP Code:
int i = 100;
Thanks.
Hello, Ive been trying to get the digits that exist in an integer, but I do not really know how to do that. SUppose I have:
How can I put the different digits into separate variables? For example 1, 0, 0PHP Code:
int i = 100;
Thanks.
Y3K Network http://www.y3knetwork.com
Bringing the software of the future on the net.
Use the modulus operator.
eg.
654 % 10 = 4
65 % 10 = 5
6 % 10 = 6
int i = 654 % 10;
i now contains 4
Oh I see, helpful!
I will try it. wait.
Y3K Network http://www.y3knetwork.com
Bringing the software of the future on the net.
Ok, the problem with this, is that I never know the exact number at first. So I cannot really remove the last digit and try again using % 10.
Do you have a work-around for that?
Y3K Network http://www.y3knetwork.com
Bringing the software of the future on the net.
sure. enclose the entire process in a loop looking for a given value. The value is that the number you're working on remains greater than 9. After each modulus, decrease the initial input value by factor of 10. Store each modulus in an array for later use.
Code:int input = //whatever int digitArray[12]; int index = -1; while(input > 9) { digitArray[++index] = input % 10; input /= 10; }
Set a proper value for MaxDigits. In this case, the digits will be 0 0 0 0 1 5 3 8. If you only want the valuable digits (non-preceeding zeros) calculate MaxDigits using 10-logarithm (log10 ? I've never used it) but then you have to modify the arrays to be allocated dynamically.Code:#define MaxDigits 8 void SplitDigits(int Number, int* DigitArray) { for(int i=(MaxDigits-1); i>=0; i++) { DigitArray[i] = Number % 10; Number /= 10; } } int main() { int DigitArray[MaxDigits]; int Number = 1538; SplitDigits(Number, DigitArray); for(int i=0; i<MaxDigits; i++) { cout << DigitArray[i] << endl; } return 0; }
MagosX.com
Give a man a fish and you feed him for a day.
Teach a man to fish and you feed him for a lifetime.
Ok, will combine all your posts.
Thank you so much.
Y3K Network http://www.y3knetwork.com
Bringing the software of the future on the net.
Thanks a lot, it works.!!!!
Y3K Network http://www.y3knetwork.com
Bringing the software of the future on the net.
This fragment works for an any digit number (within long limits)
void main()
{
long digit=12345;
while(digit>0)
{
cout<<digit%10<<endl;
digit/=10;
}
}
Happy Hunting...
Definition of Programmer : A red-eyed mumbling mammal capable of conversing with inanimate objects.
Happy Hunting...
The Root