# square c++ problem

Discussion in 'Homework Help' started by klikaa, Jan 26, 2014.

1. ### klikaa Thread Starter New Member

Jan 26, 2014
3
0
The part
for(int i=1; i<n; i++)
{
x=sqrt(y*i);
cout<<"x"<<i<<": "<<x<<endl;
}

isn't working wll, for some elements the result is non, i thought that i because the numbers are complex, but not with include complex i get the same resut.. can anyone help me

Code ( (Unknown Language)):
1.
2. #include<iostream>
3. #include<math.h>
4. #include <complex>
5. using namespace std;
6.
7. int main() {
8. int n,elem[20];
9. float y[20],A[20];
10. complex<float>  x[20];
11.
12. cout<<"Number of elements?"<<endl;
13. cin>>n;
14.     cout<<"Insert elements:"<<endl;
15. for(int i=0; i<n; i++)     {
16. cin>>elem[i];              }
17.
18.  A[0]=pow(elem[0],2);
19.
20. for(int j=1; j<n; j++)     {
21. A[j]=pow(elem[j],2);
22.
23. int i=1;
24.             while((i+j)<=n-1&&(i<=j))             {
25.  A[j]=A[j]+pow((-1),i)*2*(elem[j-i]*elem[j+i]);
26. i=i+1;                          }
27.
28. cout<<"A"<<j<<":"<<A[j]<<endl;               }
29.
30.  for(int i=1; i<n; i++)     {
31.  y[i]=A[i]/-A[i-1];
32.  cout<<"y"<<i<<": "<<y[i]<<endl;     }
33.
34. for(int i=1; i<n; i++)     {
35. x[i]=sqrt(y[i]*i);
36. cout<<"x"<<i<<": "<<x[i]<<endl;     }  }[/i][/i][/i][/i][/i][/i][/i]

Last edited by a moderator: Jan 27, 2014
2. ### blah2222 Well-Known Member

May 3, 2010
573
36
Code ( (Unknown Language)):
1.
2.  for(int i=1; i<n; i++)     {
3.  y[i]=A[i]/-A[i-1];
4.  cout<<"y"<<i<<": "<<y[i]<<endl;     }
5.
6. for(int i=1; i<n; i++)     {
7. x[i]=sqrt(y[i]*i);
8. cout<<"x"<<i<<": "<<x[i]<<endl;     }  }
9. [/i][/i][/i][/i][/i][/i]

The sqrt() function requires positive input values or else the result will be complex. You declare the array 'y' as an array of floats. Complex values require two float numbers each, one for the real part and the other for the imaginary.

From your code you have "y=A/-A[i-1];" which most likely will result in negative values to occur.

Look into how the sqrt() function operates and if it is capable of outputting complex values (I don't know off-hand) and declare your variables appropriately. If you don't want complex values, then put in an if/else to avoid negative 'y' values from being inputs to the sqrt() function.

3. ### shteii01 AAC Fanatic!

Feb 19, 2010
3,922
601
Array y[20] is from y[0] to y[20].
Array x[20] is from x[0] to x[20].

n is assigned by user. If user makes n larger than 21, then you have a problem because y[21] does not exist because your last cell is y[20].

4. ### n1ist Senior Member

Mar 8, 2009
171
16
y[20] doesn't exist either. float y[20]; declares a 20-element array with indices 0..19
/mike