在C++中编程,将 3 个数字发送到一个函数,然后计算这 3 个数字的平均函数

Program in C++ that takes 3 numbers and send them to a function and then calculate the average function of these 3 numbers

本文关键字:数字 函数 然后 一个 计算 编程 C++      更新时间:2023-10-16

C++中的程序,它接受 3 个数字并将它们发送到一个函数,然后计算这 3 个数字的平均函数。


我知道如何在不使用函数的情况下做到这一点,例如对于任何 n 个数字,我有以下程序:

#include<stdio.h>
int main()
{

int n, i;
float sum = 0, x;
printf("Enter number of elements:  ");
scanf("%d", &n);
printf("nnnEnter %d elementsnn", n);
for(i = 0; i < n; i++)
{
scanf("%f", &x);
sum += x;
}
printf("nnnAverage of the entered numbers is =  %f", (sum/n));
return 0;
}

或者这个使用数组来做到这一点:

#include <iostream>
using namespace std;
int main()
{
int n, i;
float num[100], sum=0.0, average;
cout << "Enter the numbers of data: ";
cin >> n;
while (n > 100 || n <= 0)
{
cout << "Error! number should in range of (1 to 100)." << endl;
cout << "Enter the number again: ";
cin >> n;
}
for(i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
sum += num[i];
}
average = sum / n;
cout << "Average = " << average;
return 0;
}

但是是否可以使用函数?如果是,那么如何?非常感谢您的帮助。

作为使用基本类型存储值的替代方法C++提供了 std::vector 来处理数字存储(具有自动内存管理(而不是普通的旧数组,并且它提供了许多工具,如 std::accumulate。使用 C++ 提供的功能可以大大减少您的功能:

double avg (std::vector<int>& i)
{
/* return sum of elements divided by the number of elements */
return std::accumulate (i.begin(), i.end(), 0) / static_cast<double>(i.size());
}

事实上,一个完整的示例只需要十几行额外的行,例如

#include <iostream>
#include <vector>
#include <numeric>
double avg (std::vector<int>& i)
{
/* return sum of elements divided by the number of elements */
return std::accumulate (i.begin(), i.end(), 0) / static_cast<double>(i.size());
}
int main (void) {
int n;                                          /* temporary integer */
std::vector<int> v {};                          /* vector of int */
while (std::cin >> n)                           /* while good integer read */
v.push_back(n);                             /* add to vector */
std::cout << "naverage: " << avg(v) << 'n';   /* output result */
}

上面,输入取自stdin,它将处理您想要输入的任意数量的整数(或从文件重定向作为输入(。std::accumulate只是将向量中存储的整数求和,然后要完成平均值,您只需除以元素的数量(强制转换为double以防止整数除法(。

示例使用/输出

$ ./bin/accumulate_vect
10
20
34
done
average: 21.3333

(注意:您可以输入任何非整数(或手动EOF(来结束值的输入,"done"上面只是简单地使用过,但它也可以是'q'"gorilla"- 任何非整数(

同时使用普通旧数组是件好事(因为有很多遗留代码使用它们(,但同样好的是知道编写的新代码可以利用C++现在提供的漂亮容器和数字例程(并且已经有十年左右了(。

因此,我为您创建了两个选项,一个使用向量,这真的很舒服,因为您可以使用函数成员找出大小,另一个使用数组找出大小

#include <iostream>
#include <vector>
float average(std::vector<int> vec)
{
float sum = 0;
for (int i = 0; i < vec.size(); ++i)
{
sum += vec[i];
}
sum /= vec.size();
return sum;
}
float average(int arr[],const int n)
{
float sum = 0;
for (int i = 0; i < n; ++i)
{
sum += arr[i];
}
sum /= n;
return sum;
}
int main() {
std::vector<int> vec = { 1,2,3,4,5,6,99};
int arr[7] = { 1,2,3,4,5,6,99 };
std::cout << average(vec) << " " << average(arr, 7);
}

这是一个示例,旨在让您了解需要做什么。您可以通过以下方式执行此操作:

// we pass an array "a" that has N elements
double average(int a[], const int N)
{
int sum = 0;
// we go through each element and we sum them up
for(int i = 0; i < N; ++i)
{
sum+=a[i];
}
// we divide the sum by the number of elements
// but we first have to multiply the number of elements by 1.0
// in order to prevent integer division from happening
return sum/(N*1.0);
}
int main() 
{
const int N = 3;
int a[N];
cin >> a[0] >> a[1] >> a[2];
cout << average(a, N) << endl;
return 0;
}
如何在

不使用函数的情况下做到这一点

很简单。只需将代码放入一个函数中,我们将其称为calculateAverage并从中return平均值。这个函数应该把什么作为输入?

  • 数字列表 (array of numbers(
  • 总数 (n(

因此,让我们首先从用户那里获取输入并将其放入数组中,您已经完成了:

for(int i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
}

现在,让我们做一个小函数,即calculateAverage()

int calculateAverage(int numbers[], int total)
{
int sum = 0; // always initialize your variables
for(int i = 0; i < total; ++i)
{
sum += numbers[i];
}
const int average = sum / total; // it is constant and should never change
// so we qualify it as 'const'
//return this value
return average
}

这里有几个要点需要注意。

  • 当您将数组传递到函数中时,您将丢失大小信息,即它包含多少元素或可以包含多少元素。这是因为它衰减成指针。那么我们如何解决这个问题呢?有几种方法,
    • 在函数中传递大小信息,就像我们传递total
    • 使用std::vector(当您不知道用户将输入多少元素时(。std::vector是一个动态数组,它将根据需要增长。如果您事先知道元素的数量,则可以使用std::array

代码存在一些问题:

using namespace std;

别这样。相反,如果你想从std中得到一些东西,例如,cout你可以做:

using std::cout
using std::cin
...

或者你可以每次都写std::cout

int n, i;
float num[100], sum=0.0, average;

在使用变量之前,请始终对其进行初始化。如果您不知道它们应该初始化为的值,只需使用{}进行默认初始化;

int n{}, i{};
float num[100]{}, sum=0.0, average{};

在单独的行上声明变量不是强制性的,而是很好的做法。这使您的代码更具可读性。

相关文章: