ベクトルの長さと正規化
#include <iostream> #include <cmath> // sqrt template <class T> struct vector2 { T x, y; vector2(const T& x, const T& y) : x(x), y(y) {} // ベクトルの長さ T norm2() const { return std::sqrt(x * x + y * y); } // 正規化(ベクトルの長さを1にする) void normalize() { float mag = 1 / norm2(); x *= mag; y *= mag; } }; int main() { vector2<float> v(2, 3); std::cout << v.norm2() << std::endl; // 3.60555 v.normalize(); std::cout << v.norm2() << std::endl; // 1 }