提问人:Kimberly 提问时间:4/3/2023 更新时间:4/3/2023 访问量:113
如何使用函数查找数组的总和和平均值并按引用调用 C++
How to find the sum and average of an array using a function and call by reference C++
问:
我们被告知要编写一个函数,该函数接受一个双精度数组并传回数组中数字的总和和平均值
代码如下:
#include <iostream>
#include <iomanip>
using namespace std;
void sumAverage (double[], int, int &, int &);
int main()
{
double A[10] = { 3.54, 8.12, 39.04, 12.23, 49.32, 90.23};
int sum, average;
sumAverage (A, 10, sum, average);
cout << "The sum is " << A[sum] << endl << endl;
cout << "The average is " << A[average];
return 0;
}
void sumAverage (double array[], int numvalues, int &Asum, int &Aaverage)
{
double sum = 0;
for (int sub = 0; sub < numvalues; sub++)
{
sum += array[sub];
Asum = sum;
Aaverage = Asum / numvalues;
}
}
我觉得我缺少或没有得到一些东西,因为我对编码还很陌生。任何帮助将不胜感激
答:
0赞
cppNewbie
4/3/2023
#1
我认为你的代码是这个意思。
cout << "The sum is " << sum << endl << endl;
cout << "The average is " << average;
如果要打印小数点,则需要更改“sum”和“average”的数据类型
double sum,average;
1赞
yusril aprial
4/3/2023
#2
给定的代码存在一些问题: 1)输入数组只有 6 个元素,但函数调用指定数组中有 10 个元素。这可能导致访问越界内存,这是未定义的行为。2)该函数应该传回求和和平均值,但实际上它传回了数组中求和平均值的索引。这是不正确的。3)平均值的计算不正确。它应该是 Aaverage = sum / numvalues。 下面是代码的更正版本:
#include <iostream>
#include <iomanip>
using namespace std;
void sumAverage(double[], int, double &, double &);
int main()
{
double A[6] = {3.54, 8.12, 39.04, 12.23, 49.32, 90.23};
double sum, average;
sumAverage(A, 6, sum, average);
cout << "The sum is " << sum << endl;
cout << "The average is " << fixed << setprecision(2) << average << endl;
return 0;
}
void sumAverage(double array[], int numvalues, double &Asum, double &Aaverage)
{
double sum = 0;
for (int sub = 0; sub < numvalues; sub++)
{
sum += array[sub];
}
Asum = sum;
Aaverage = sum / numvalues;
}
评论
sumAverage
sum
int
A[sum]
double
Asum
Aaverage
int
2.1
1.2
3.3
1.65
int
sum
3
1