【发布时间】:2020-06-02 05:59:42
【问题描述】:
用 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("\n\n\nEnter %d elements\n\n", n);
for(i = 0; i < n; i++)
{
scanf("%f", &x);
sum += x;
}
printf("\n\n\nAverage 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;
}
但是可以使用函数吗?如果可以,那么如何使用?非常感谢您的帮助。
【问题讨论】:
-
是的,可以使用函数。只需将
num和n传递给函数即可。 -
在 C++ 中,使用
std::vector代替数组会更合适。 -
C 与 C++ 不同。阅读 more about them,对于 C++,阅读 this book。对于 C,请阅读 that one
-
@Basile Starynkevitch,感谢您的链接
-
这是另一个需要考虑的:Why is “using namespace std;” considered bad practice?。替我向 Tex 打个招呼....