Results 1 to 5 of 5
Thread: Finding the length of a vector
 04062013, 02:56 AM #1Member
 Join Date
 Feb 2013
 Posts
 33
 Rep Power
 0
Finding the length of a vector
I'm not sure if I did this right but when I run it, the answer is 0.0. I want to know what I am doing wrong.
What i'm asked to do:
Write a function that finds the length of a vector.
double Length( double X[ ] )
The length of a vector is the square root of the sum of the squares of the elements in the array. Use dynamic memory and allocate 10 elements for X. Initialize the data values of X to the counting numbers 110.
Java Code:class Length { public Length() {} double length ( double[] X ) { double sum = 0; double l = 0; for ( int i = 1; i < X.length; i++ ) { sum += Math.pow(X[i], 2); l = Math.sqrt(sum); return l; } } }
Java Code:class LengthTest { public static void main( String [] args ) { Length myLength = new Length(); double[] X; X = new double [ 11 ]; System.out.println( ); System.out.println("Length of the vector is " + myLength.length(X) + "."); System.out.println( ); } }
Last edited by wheehoowaffles; 04062013 at 03:14 AM.
 04062013, 03:03 AM #2Moderator
 Join Date
 Feb 2009
 Location
 New Zealand
 Posts
 4,712
 Rep Power
 15
Re: Finding the length of a vector
What are the numbers in the array array when you pass it to the length() method?
Also it would be a good idea to add some braces to the for loop in the length() method to show clearly just what is being repeated each time around the loop. (although this isn't the problem here. but every ounce of clarity helps when  or before  things go wrong!)
 04062013, 03:13 AM #3Member
 Join Date
 Feb 2013
 Posts
 33
 Rep Power
 0
Re: Finding the length of a vector
It said to initialize the data values of X from 110 so I tried doing it by using a for loop.
 04062013, 03:26 AM #4Moderator
 Join Date
 Feb 2009
 Location
 New Zealand
 Posts
 4,712
 Rep Power
 15
Re: Finding the length of a vector
You see that the place to do that initialisation is in the main() method, right?
 04062013, 03:34 AM #5Member
 Join Date
 Feb 2013
 Posts
 33
 Rep Power
 0
Similar Threads

Length of an Array: length() or just length ?
By Jack_Tauson_Sr in forum New To JavaReplies: 8Last Post: 03182013, 09:16 PM 
finding possible ordering set of vector
By sara12345 in forum New To JavaReplies: 7Last Post: 03162010, 09:35 AM 
finding length on a number
By thekrazykid in forum New To JavaReplies: 8Last Post: 12122008, 09:07 PM 
Finding elements in a vector
By Java Tip in forum java.langReplies: 0Last Post: 04142008, 08:37 PM 
Finding the exact length of a string in a JLabel (in pixels)
By Clarkey in forum Advanced JavaReplies: 2Last Post: 03252008, 06:49 AM
Bookmarks