I'm trying to make a function receiving as a parameter an array, an returning its int equivalent. For instance, when the array "set[]={3,2,1}", is passed on the function, it will return the integer value 321.
#include <cstdlib>
#include <iostream>
#include <math.h>
using namespace std;
int ArraytoInt(int array[],int n){
int sum=0;
int product;
for(int i=0; i< n ; i++){
product= (int) pow(10,i);
sum=sum+ (array[n-i-1]*product);
printf("\n %i %i ", product,sum);
}
return sum;
}
int main(){
int array[3];
array[0]=3;
array[1]=2;
array[2]=1;
int number=ArraytoInt(array,3);
int product;
product= (int) pow(10,2 );
printf("\n %i %i \n", number, product);
system("PAUSE");
return EXIT_SUCCESS;
}
Output:
1 1
10 21
99 318
318 100
I don't get the expected result due to a very strange issue. Notice that in the function pow(10,2) is computed as 99, whereas in the main function is computed as 100, despite being wrote in exactly the same way!!!
Such are floating point numbers. pow probably returns 99.99..9 but (int) rounds that down. The best solution would be to use a counter of your own (create another variable, multiply it by 10 on every cycle). Though you could simply try (pow(10, i)+0.5). Adding 0.5 makes it round to the nearest integer instead of always down.
#include <cstdlib>
#include <iostream>
#include <math.h>
usingnamespace std;
int ArraytoInt(int array[],int n)
{
int sum=0;
int product;
for(int i=0; i< n ; i++)
{
product= (int) pow(10,i);
sum=sum+ (array[n-i-1]*product);
printf("\n %i %i ", product,sum);
}
return sum;
}
int main()
{
int array[3];
array[0]=3;
array[1]=2;
array[2]=1;
int number=ArraytoInt(array,3);
int product;
product= (int) pow(10,2 );
printf("\n %i %i \n", number, product);
system("PAUSE");
return EXIT_SUCCESS;
}
That looks a bit better.
sum=sum+ (array[n-i-1]*product);
What kind of magic you are trying to do here with [n-i-1]?
Is that some school exercise? Because the probably most easiest way to solve this would be to read int as char, then add chars to one string and use atoi() to convert from string to integer.
here a simpler one
void rtrn(int A[])
{int N,i,value=0;
cout<<"Enter Number Of Elements In Array";
cin>>"\n">>N;
cout<<"\nEnter Elements";
for(i=0;i<N;i++)
{cin>>A[i];}
for(i=N-1;i>=0;i--)
{value+=A[i]*pow((N-i-1),10);} \\pow((N-i-1),10) in simple language is 10^{N-i-1}
return value;}
Sorry for my not so appealing code I'm new to this forum. I'm using Dev-C++, the rare thing here is that when using NetBeans environment the output is as expected. The sole problem here is when raising 10 the second power, and some powers, in which the result is always 9999...(n numbers of 9's), but strangely enough that only happens in Dev-C++.