square c++ problem

Thread Starter

klikaa

Joined Jan 26, 2014
3
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


Rich (BB code):
#include<iostream> 
#include<math.h> 
#include <complex> 
using namespace std; 

int main() {     
int n,elem[20];     
float y[20],A[20];     
complex<float>  x[20]; 

cout<<"Number of elements?"<<endl;     
cin>>n; 
    cout<<"Insert elements:"<<endl;     
for(int i=0; i<n; i++)     {         
cin>>elem;              }

 A[0]=pow(elem[0],2);          

for(int j=1; j<n; j++)     {         
A[j]=pow(elem[j],2);                  

int i=1; 
            while((i+j)<=n-1&&(i<=j))             {
 A[j]=A[j]+pow((-1),i)*2*(elem[j-i]*elem[j+i]);                 
i=i+1;                          }                   

cout<<"A"<<j<<":"<<A[j]<<endl;               }

 for(int i=1; i<n; i++)     {
 y=A/-A[i-1];
 cout<<"y"<<i<<": "<<y<<endl;     }          

for(int i=1; i<n; i++)     {         
x=sqrt(y*i);         
cout<<"x"<<i<<": "<<x<<endl;     }  }
 
Last edited by a moderator:

blah2222

Joined May 3, 2010
582
Rich (BB code):
 for(int i=1; i<n; i++)     {
 y=A/-A[i-1];
 cout<<"y"<<i<<": "<<y<<endl;     }          

for(int i=1; i<n; i++)     {         
x=sqrt(y*i);         
cout<<"x"<<i<<": "<<x<<endl;     }  }


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.
 

shteii01

Joined Feb 19, 2010
4,644
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].
 
Top