import java.util.Random;
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
// Random number generator
Random rng = new Random();
// Get vector dimensions
Scanner input = new Scanner(System.in);
System.out.print("\nHow many dimensions in vector A[n]? ");
int dimensions = input.nextInt();
// fill vector with random values
double[] vector = new double[dimensions];
for(int index = 0; index < dimensions; index++){
vector[index] = rng.nextDouble();
}
displayVector(vector);
// get multiplier
System.out.print("What shall we multiply the vector by? ");
double scalar = input.nextFloat();
// multiply each component by scaling factor
for(int index = 0; index < dimensions; index++){
vector[index] *= scalar;
}
displayVector(vector);
input.close(); // prevent resource leak
} // main
// display vector
static void displayVector(double[] vector) {
String output = "v[";
for(double dimension : vector){
output += String.format(" %4.4f", dimension);
}
System.out.println(output + " ]");
}
} // Main
Thanks a lot. I send you the love of the whole worldMultiplying a vector by a scalar
Java:import java.util.Random; import java.util.Scanner; public class Main{ public static void main(String[] args) { // Random number generator Random rng = new Random(); // Get vector dimensions Scanner input = new Scanner(System.in); System.out.print("\nHow many dimensions in vector A[n]? "); int dimensions = input.nextInt(); // fill vector with random values double[] vector = new double[dimensions]; for(int index = 0; index < dimensions; index++){ vector[index] = rng.nextDouble(); } displayVector(vector); // get multiplier System.out.print("What shall we multiply the vector by? "); double scalar = input.nextFloat(); // multiply each component by scaling factor for(int index = 0; index < dimensions; index++){ vector[index] *= scalar; } displayVector(vector); input.close(); // prevent resource leak } // main // display vector static void displayVector(double[] vector) { String output = "v["; for(double dimension : vector){ output += String.format(" %4.4f", dimension); } System.out.println(output + " ]"); } } // Main
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.