问题描述
我有下面显示的这段代码,它应该手动计算随机生成的向量的范数。但是,我一直将输出打印到终端为 0。为什么会这样?
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <ctime>
using namespace std;
double Computenorm(const vector<double>& x) {
double result = 0.0;
for (auto a : x) {
double result = result + a*a;
}
return sqrt(result);
}
int main() {
// Declare variables
#if 0
int n;
cin >> n
#else
int n = 1000;
#endif
if (n == 0) {
cout << "N must be > 0" << endl;
}
vector<double> x(n,0.0);
// Seed the random number generate with the current epoch time
srand(time(0));
// Generate random numbers and print them to the screen
generate(x.begin(),x.end(),[] { return (double)rand()/RAND_MAX; });
// Print out the values computed by BLAS and manually
// cout << "BLAS norm: " << cblas_dnrm2(n,&x[0],1) << endl;
cout << "Manual norm: " << Computenorm(x) << endl;
// cout << "x(n): " << x[n] << endl;
return 0;
}
解决方法
double result = result + a*a;
这在循环内声明了一个新变量,因此另一个 result
变量不会改变,这就是返回 0 的原因。
要修复它,只需执行 result = result + a*a
或 result += a*a
:
double ComputeNorm(const vector<double>& x) {
double result = 0.0;
for (auto a : x) {
result = result + a*a;
}
return sqrt(result);
}
,
在 ComputeNorm
函数的 for 循环中,您在每次迭代中都重新声明了 result
,而循环外的 result
从未改变。
相反,您可能希望 result = result + a*a
在那里。
我无法评论,因为我没有足够的声誉,但我想评论的是,您在函数 `ComputeNorm 中两次声明了局部变量 result
。
这可能是您问题的根源。