我正在尝试计算向量中所有浮点数的总和。用户输入是向量和浮点数中元素的数量。由于某种原因,总和打印为3.01734 ...
代码:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
float n, temp, sum; // integer variables declaration
vector<float> nums; // declaration of "nums" vector
cin>>n; // number of elements in the vector "nums"
for(int i=0; i<n; i++){
cin >> temp; // user input for "temp" variable
nums.push_back(temp); // adds(pushes) "temp" to "nums" vectors
}
for(int j=0; j<(short)nums.size(); j++){
sum+=nums.at(j); // adds the "j" element of "nums" vetor to sum
}
cout << sum; // outputs the sum
return 0;
}
编辑: 该代码不起作用,因为未对“ sum”进行初始化。我们需要手动将“ sum”初始化为0.0,否则,它将存储内存“垃圾”;如果将其设置为0,它将“ sum”(这是一个浮点数)四舍五入为整数(整数) 。
答案 0 :(得分:2)
当您不初始化变量时,它们以“垃圾”值开始,该值一直在其内存地址中。因此,当您遍历向量并每次将其增加每个值时,实际上您已经从开始时的随机数开始计数,而不是从0开始计数。这是(未经测试的)方法:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
float n = 0, temp = 0, sum = 0; // initialized variables as 0.
vector<float> nums;
cin >> n;
for(int i=0; i<n; i++){
cin >> temp;
nums.push_back(temp);
}
nums.resize(n); // to be honest I don't really understand why this is needed
// note: you can use the letter i again, when you declare a variable inside a scope,
// it's only declared for that scope.
for(int j=0; j<(short)nums.size(); j++){
sum+=nums.at(j);
}
cout << sum;
return 0;
}