给定三个表示X,Y的整数, 和3-D向量的Z坐标,任务是找到该向量的大小。
例子:
Input: X = 1, Y = 2, Z = 2
Output: 3
Explanation: Magnitude of the vector is equal to √9 =3
Input: X = 0, Y = 4, Z = 3
Output: 5
方法:可以通过求解方程√(X 2 + Y 2 + Z 2 )来计算向量的大小。请按照以下步骤解决问题:
- 将X,Y和Z坐标的平方和存储在一个变量中,例如sum。
- 初始化一个变量,例如幅度,以存储和的平方根。
- 打印幅度值作为所需结果。
下面是上述方法的实现:
C++14
// C++ program for the above approach
#include
using namespace std;
// Function to calculate magnitude
// of a 3 dimensional vector
float vectorMagnitude(int x, int y, int z)
{
// Stores the sum of squares
// of coordinates of a vector
int sum = x * x + y * y + z * z;
// Return the magnitude
return sqrt(sum);
}
// Driver Code
int main()
{
int x = 1;
int y = 2;
int z = 3;
cout << vectorMagnitude(x, y, z);
return 0;
}
Java
// Java program for the above approach
class GFG{
// Function to calculate magnitude
// of a 3 dimensional vector
private static double vectorMagnitude(int x, int y,
int z)
{
// Stores the sum of squares
// of coordinates of a vector
int sum = x * x + y * y + z * z;
// Return the magnitude
return Math.sqrt(sum);
}
// Driver code
public static void main(String[] args)
{
int x = 1;
int y = 2;
int z = 3;
System.out.print(vectorMagnitude(x, y, z));
}
}
// This code is contributed by abhinavjain194
Python3
# Python3 program for the above approach
from math import sqrt
# Function to calculate magnitude
# of a 3 dimensional vector
def vectorMagnitude(x, y, z):
# Stores the sum of squares
# of coordinates of a vector
sum = x * x + y * y + z * z
# Return the magnitude
return sqrt(sum)
# Driver code
x = 1
y = 2
z = 3
print(vectorMagnitude(x, y, z))
# This code is contributed by abhinavjain194
C#
// C# program for the above approach
using System;
class GFG{
// Function to calculate magnitude
// of a 3 dimensional vector
private static double vectorMagnitude(int x, int y,
int z)
{
// Stores the sum of squares
// of coordinates of a vector
int sum = x * x + y * y + z * z;
// Return the magnitude
return Math.Sqrt(sum);
}
// Driver code
static void Main()
{
int x = 1;
int y = 2;
int z = 3;
Console.Write(vectorMagnitude(x, y, z));
}
}
// This code is contributed by abhinavjain194
输出:
3.74166
时间复杂度: O(1)
辅助空间: O(1)