Let's say I have an array where a[0] = 9, a[1] = 8, a[2] = 7, a[3] = 6
I want to place each element together to form just one number, so that i could have int num = 9876. Is this possible?
In C++, how do you convert an array of integers to form just one number?
Sure it's possible... a *hint* would be... Use multiples of 10!
Reply:Here is a way:
#include %26lt;stdio.h%26gt;
#define SIZE 4
int powers( num, power )
{
if ( power == 0 )
return 1;
else
{
return ( num * powers( num, power-1 ) );
}
}
int main()
{
int arr[SIZE] = { 9, 8, 7, 6 };
int i;
int num = 0;
int largest = powers( 10, SIZE );
for ( i = 0; i %26lt; SIZE; ++i )
{
largest = largest/10;
num += arr[ i ] * largest;
}
printf( "The number is: %d\n", num );
return 0;
}
Reply:Here is a function for you.
//values is the array and size is the length of the array
// do not pad the array with zeros on the left.
int combine(int* values, int size)
{
// setup and initial value as the first one in the array
int result = values[0];
// loop through all the rest of the values
// push the old numbers over by 1 place *10
// and add the new one on the end + val
for(i=1;i%26lt;size;i++)
result += result*10 + values[i];
return result;
}
Reply:You could try using:
String.Concat(x);
to create a string from the elements of array x. You would then have "9876", but it would be a string, not a number. You could then cast it into an integer easily if you needed to carry out mathematical functions on it. I'm a bit rusty, so I'm not sure whether you will need to import String.h or whether it will be included in system namespace.
Good luck.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment