在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++中的程序,它接受 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{};
在单独的行上声明变量不是强制性的,而是很好的做法。这使您的代码更具可读性。
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 函数在许多数字上转换为基数 1 时减去 2?
- 函数如何使用引用返回所需的数字?
- 当我尝试在 Main 中调用插入函数时,它不是取数字?
- C++ 函数,用于查找传入的 N 个数字的平均值、总和、最小值和最大值
- 如何在 setup() 函数中使用数字引脚转动电机?
- C++ python 中的函数返回数字而不是字符串
- 如何在不使用 C++ 中的数组或函数的情况下查找 N 位数字的所有排列
- 将 C 函数转换为 C++ 以检查数字是否有效
- 在C++中编程,将 3 个数字发送到一个函数,然后计算这 3 个数字的平均函数
- 是否有一个 std::set 函数来确定不超过数字 x 的最大元素?
- 在 c++ 中将数字转换为矢量数组的函数
- 使用带有一个参数函数的递归找到数字的平方
- 我想使用 std::stoi 函数在 cpp 中将字符串转换为整数,因为我想在字符串中找到不同数字的总和(在下级酶中)
- 为什么当我在 c++ 中运行函数时,我的代码显示数字 53
- 我有模板功能.通过使用函数std::for_each,用这个容器中的最大数字替换每个正数
- 如何用不同的参数类型和数字回调函数
- 我必须更改我的数字最后一个数字和第一个数字,但不要使用仅带有整数或循环的函数.例如从 12345 到 52341
- 素数检查 C++ 函数输出非素数的数字
- C++ 在地板函数之后以十六进制打印数字