fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <math.h>
  4. #include <stdlib.h>
  5.  
  6. using namespace std;
  7.  
  8. int main()
  9. {
  10. int i;
  11. int n;
  12. double sum_squares = 0;
  13. double euclid_dist = 0;
  14.  
  15. // initialize random number generator with random seed 123
  16.  
  17. srand48(123);
  18.  
  19. // two vectors of elements of type double
  20.  
  21. vector<double> u;
  22. vector<double> v;
  23.  
  24. // read vector size n from input
  25.  
  26. cin >> n;
  27.  
  28. // resize the vectors to accommodate n elements
  29.  
  30. u.resize(n);
  31. v.resize(n);
  32.  
  33. // generate both vectors random, each variable from
  34. // uniform distribution over interval [0,1)
  35.  
  36. for (i=0; i<n; i++)
  37. {
  38. u[i] = drand48();
  39. v[i] = drand48();
  40. }
  41.  
  42. // compute the sum of square differences between the
  43. // vector elements
  44.  
  45. for (i=0; i<n; i++)
  46. {
  47. double diff = u[i] - v[i];
  48. sum_squares += (diff*diff);
  49. }
  50.  
  51. // Euclidean distance is the square root of the sum of
  52. // square differences
  53.  
  54. euclid_dist = sqrt(sum_squares);
  55.  
  56. // print out the sum of squares and the distance
  57.  
  58. cout << "sum of squares: " << sum_squares << endl;
  59. cout << "Euclidean distance: " << euclid_dist << endl;
  60.  
  61. // return from main with 0
  62.  
  63. return 0;
  64. }
  65.  
Success #stdin #stdout 0.01s 2820KB
stdin
1077
stdout
sum of squares:     183.494
Euclidean distance: 13.546