解答

  1. /// Calculate the magnitude of the given vector.
  2. fn magnitude(vector: &[f64; 3]) -> f64 {
  3. let mut mag_squared = 0.0;
  4. for coord in vector {
  5. mag_squared += coord * coord;
  6. }
  7. mag_squared.sqrt()
  8. }
  9. /// Change the magnitude of the vector to 1.0 without changing its direction.
  10. fn normalize(vector: &mut [f64; 3]) {
  11. let mag = magnitude(vector);
  12. for item in vector {
  13. *item /= mag;
  14. }
  15. }
  16. fn main() {
  17. println!("Magnitude of a unit vector: {}", magnitude(&[0.0, 1.0, 0.0]));
  18. let mut v = [1.0, 2.0, 9.0];
  19. println!("Magnitude of {v:?}: {}", magnitude(&v));
  20. normalize(&mut v);
  21. println!("Magnitude of {v:?} after normalization: {}", magnitude(&v));
  22. }