两个vector相乘是怎么算的
时间: 2024-04-02 20:34:54 浏览: 16
两个向量相乘有两种情况:点积(内积)和叉积(外积)。
1. 点积(内积):两个向量 A 和 B 的点积(内积)结果等于它们对应位置元素的乘积之和。
A · B = A1B1 + A2B2 + ... + AnBn
其中,A1、A2、...、An 和 B1、B2、...、Bn 分别是 A 和 B 向量的元素。点积的结果是一个标量,表示两个向量在空间中的夹角余弦值。
2. 叉积(外积):两个三维向量 A 和 B 的叉积(外积)结果是一个新的向量 C,其大小等于 A 和 B 所在平行四边形的面积,方向垂直于平行四边形所在的平面,并遵循右手定则。
C = A × B
其中,× 表示叉积运算符,A 和 B 为三维向量。叉积的计算方法比较复杂,涉及到向量的坐标、行列式等内容,这里不再详细讲解。
相关问题
c++ vector相乘
若要实现 C++ 中 vector 的相乘,可以利用循环将两个 vector 对应位置的元素相乘再累加得到结果。代码如下:
```cpp
#include <vector>
int vectorDotProduct(std::vector<int>& vec1, std::vector<int>& vec2) {
if (vec1.size() != vec2.size()) {
// 处理两个 vector 大小不一致的情况
return 0;
}
int res = 0;
for (int i = 0; i < vec1.size(); ++i) {
res += vec1[i] * vec2[i];
}
return res;
}
```
用c++设计一个实现两个长整型相乘的程序。
好的,这里给您提供一种可能的实现方式:
```c++
#include<iostream>
#include<string>
using namespace std;
string multiply(string num1, string num2) {
int n1 = num1.size();
int n2 = num2.size();
if (n1 == 0 || n2 == 0)
return "0";
// 用vector存储相乘的结果
vector<int> result(n1 + n2, 0);
// 从num1的最后一位开始,逐位与num2相乘
int i_n1 = 0;
int i_n2 = 0;
for (int i = n1 - 1; i >= 0; i--) {
int carry = 0;
int n1 = num1[i] - '0';
// 每次与num2的所有位相乘
i_n2 = 0;
for (int j = n2 - 1; j >= 0; j--) {
int n2 = num2[j] - '0';
int sum = n1 * n2 + result[i_n1 + i_n2] + carry;
carry = sum / 10;
result[i_n1 + i_n2] = sum % 10;
i_n2++;
}
// 处理进位
if (carry > 0)
result[i_n1 + i_n2] += carry;
i_n1++;
}
// 去掉前导0
int i = result.size() - 1;
while (i >= 0 && result[i] == 0)
i--;
if (i == -1)
return "0";
// 把vector转换为string
string s = "";
while (i >= 0)
s += to_string(result[i--]);
return s;
}
int main() {
string num1 = "123456789";
string num2 = "987654321";
string result = multiply(num1, num2);
cout << num1 << " * " << num2 << " = " << result << endl;
return 0;
}
```
这个程序使用了字符串来存储长整型,逐位相乘,然后用vector来存储相乘的结果,最后再把vector转换为字符串。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)