gpt4 book ai didi

c++ - vector 递归均值

转载 作者:太空宇宙 更新时间:2023-11-04 11:38:01 26 4
gpt4 key购买 nike

我编写了这个程序,它使用递归函数计算 vector 中元素的总和和平均值。用户应该输入任意数量的数字,然后在完成后按“0”。我忽略了最后一个元素,即“0”。但是,sum 函数仍然有问题,因为它忽略了 vector 中的第一个元素,因此平均值也不正确。这是代码:

    int main(void){
vector <int> series;
int n;
unsigned int nr_elem;

cout << "Type as many numbers as you want and press 0 when you are finished:";
do{
cin >> n;
series.push_back(n);
} while (n);

nr_elem = series.size()-1;
cout << "nr_elem="<< nr_elem;
cout << "\n The sum of the elements in the series is: " << sum(series, nr_elem);
cout << "\n The average of the elements is: " << average(series, nr_elem);
return 0;
}

int sum(vector<int> &series, int n){
if (n == 0)
return 0;
else
return series.at(n) + sum(series, n - 1);
}

double average(vector<int> &series, int n){
if (n == 0)
return 0;
else
return (series.at(n) + sum(series, n - 1)) / n;
}

对于输入值:10,20,50,0 我得到 nr_elem=3

                               The sum of the elements is: 70

The mean is: 23`

这是我第二次使用 vectors 进行试验,因此,我们将不胜感激任何解释和额外的更正。

最佳答案

vector 的大小由 size() 函数给出,它准确返回 vector 中元素的数量,但索引从零开始。

您没有计算求和函数中的 0(不是您插入的终端项, vector 的第一项!)元素

int sum(vector<int> &series, int n){
if (n == 0) // This is the problem, 0 isn't the last element, is the first element!
return 0;
else
return series.at(n) + sum(series, n - 1);
}

要解决(最小侵入性)改变

if (n == 0)

类似于

if (n == -1)

编辑:如果你想返回一个 double 值,你也需要处理 double 值。如果您使用整数(没有小数位)进行数学运算,您将得到一个整数结果(没有小数位)。所以你丢失了你的小数位。

另一个“丑陋”的解决方案是强制将整数转换为 double ,并在所有东西都为 double 时进行计算

double average(vector<int> &series, int n){
if (n == -1)
return 0;
else
return (static_cast<double>(series.at(n)) + static_cast<double>(sum(series, n - 1))) / static_cast<double>(n);
}

关于c++ - vector 递归均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22438116/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com