使用函数计算求和和和平均值的程序 我正在做一个C++问题,我需要生成一个随机数,这个随机数是程序将提示用户输入多少个整数。
然后我需要使用两个单独的函数:1计算并返回总和,另一个计算并返回平均值 以下是我目前的代码:使用函数计算求和和和平均值的程序 我正在做一个C++问题,我需要生成一个随机数,这个随机数是程序将提示用户输入多少个整数。,c++,C++,然后我需要使用两个单独的函数:1计算并返回总和,另一个计算并返回平均值 以下是我目前的代码: #include <iostream> #include <cstdlib> #include <ctime> using namespace std; int calculateSum(int, int); int calculateAvg(int, int, int); int main() { int sum = 0; int average
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int calculateSum(int, int);
int calculateAvg(int, int, int);
int main()
{
int sum = 0;
int average = 0;
int x;
int y;
int n = 0;
srand(time(0));
y = rand() % 10;
for (x = 1; x <= y; x++) {
cout << "Enter integer " << x << ": ";
cin >> n;
}
cout << "Sum: " << calculateSum(n, sum) << endl;
cout << "Average: " << calculateAvg(average, sum, y) << endl;
system("pause");
return 0;
}
int calculateSum(int n, int sum)
{
sum = sum + n;
return sum;
}
int calculateAvg(int average, int sum, int y)
{
average = sum / y;
return average;
}
#包括
#包括
#包括
使用名称空间std;
int计算um(int,int);
int计算avg(int,int,int);
int main()
{
整数和=0;
整数平均=0;
int x;
int-y;
int n=0;
srand(时间(0));
y=rand()%10;
对于(x=1;x您在循环中每次都覆盖n
,但最后只更新sum
。每次都更新sum
。您在循环中每次都覆盖n
,但在循环结束时只更新sum
。每次更新sum
。您的int n
只有空间r是单个整数,因此for循环只会用您输入的每个整数覆盖n
。自然,您输入的最后一个整数将是离开for循环时保存的唯一整数
您需要在for循环中调用calculateSum()
,以便它在循环的每一次迭代中递增sum
。因此,不要:
for (x = 1; x <= y; x++) {
cout << "Enter integer " << x << ": ";
cin >> n;
}
cout << "Sum: " << calculateSum(n, sum) << endl;
致:
(我还将返回类型从int
更改为void
,因为您不需要返回sum
或average
——您已经在各自的函数中修改了它们)您的int n
只能容纳一个整数,因此for循环只会用您输入的每个整数覆盖n
。当然,您输入的最后一个整数将是离开for循环时保存的唯一整数
您需要在for循环中调用calculateSum()
,以便它在循环的每一次迭代中递增sum
。因此,不要:
for (x = 1; x <= y; x++) {
cout << "Enter integer " << x << ": ";
cin >> n;
}
cout << "Sum: " << calculateSum(n, sum) << endl;
致:
(我还将返回类型从int
更改为void
,因为您不需要返回sum
或average
——您已经在各自的函数中修改了它们)问题是您应该使用数组,而不是典型的整数
而不是您当前的n
int array[10];
for(int i=0; i <=y; i++)
{
cin >>n;
array[i] = n;
}
int数组[10];
对于(int i=0;i>n;
数组[i]=n;
}
问题是您应该使用数组,而不是典型的整数
而不是您当前的n
int array[10];
for(int i=0; i <=y; i++)
{
cin >>n;
array[i] = n;
}
int数组[10];
对于(int i=0;i>n;
数组[i]=n;
}
将输入的值保存在向量中,然后使用std::acculate
请参见中的示例,将输入的值保存在向量中,然后使用std::acculate
参见中的示例我相信您可能使用了rand()
函数我相信您可能使用了rand()
函数
int array[10];
for(int i=0; i <=y; i++)
{
cin >>n;
array[i] = n;
}