| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
adding digits for integer
I have a small problem.
I want to add digits together but not the integer value. For example, if the digits are 1, 2, 3. i want d value 123. Or if the value is 12, 30, 15 i want 123015. any suggestions? |
|
#2
|
|||
|
|||
|
Take the digits as strings of single character. Concatenate them using strcat().
Then use atoi() [in C/C++] or CInt() [in VC++]. For converting concatenated string as number. |
|
#3
|
|||
|
|||
|
another way: for example, adding 1 + 2 = 12.
what you need to really do is (1*10) + 2. If you notice, you need to multiply the first number by the 10^(the number of digits in the second number). so you do you get that value? I did it for a project I'm working on by making a function called intpow(): Code:
int intpow(int the_int)
{
int i = 1;
while (the_int % i != the_int) i *= 10; //this is the important line, see below
return i;
}
so let's have a look at that line. while (the_int % i != the_int) i *= 10; that would be read "if the_int modulus i does not equal the_int, multiply i by 10 and try again until it does." if you are not familiar with the modulus(%) operator, what it does is perform division but returns only the remainder. so 5 % 2 would be 1. If you play around with inputting different numbers and mentally walking through my function, you will notice that for a function with x number of digits, the number % 10^x (10 to the power of x) = the number. if you are still confused, ask more questions and i'll help. |
![]() |
| Viewing: Dev Articles Community Forums > Programming > C/C++ Help > adding digits for integer |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|