下午好,我被要求做一个叫做void printStatistics(int n)的函数,该函数应该打印传入的n个数的平均值,和,最小和最大数。例如,如果我执行了printStatistics(5),那么我应该要求用户输入5次数字,然后打印统计信息。 我所要做的就是创建一个while循环,要求用户输入数字,直到输入负数为止,但是将其转换为要求用户输入数字n次然后打印出来的函数似乎有些麻烦。总和,平均值,最小值和最大值。这就是我所拥有的。
int main()
{
int value, sum;
int average, min, max;
int count;
sum = 0;
count = 0;
cout << "Enter a number: " << endl;
cin >> value;
min = value;
max = value;
while(value >= 0)
{
sum += value;
count++;
if(value > max)
max = value;
else if(value < min)
min = value;
cout << "Enter a numnber: " << endl;
cin >> value;
}
if(count == 0)
cout << "Nothing entered." << endl;
else
{
average = sum / count;
cout << "Average is " << average << endl;
cout << "Minimum is " << min << endl;
cout << "Maximum is " << max << endl;
cout << "Sum is " << sum << endl;
}
}
答案 0 :(得分:3)
根据我对问题的理解,您希望有一个函数(printStatistics),该函数的参数'int n'和'n'与用户希望输入的数字量相对应。然后,您要求提供这些特定的数字,然后找到该集合的MIN,MAX,SUM和AVERAGE。如果我正确理解了这一点,那么应该可以解决这个问题:
#include <iostream>
void printStatistics(int n);
void printStatistics(int n)
{
int response;
int sum = 0;
int max;
int min;
for (int i = 1; i <= n; ++i)
{
std::cout << "Please enter the number in the " << i << " position: ";
std::cin >> response;
if (i == 1)
{
min = response;
max = response;
}
(min > response) ? min = response : min = min;
(max < response) ? max = response : max = max;
sum += response;
}
std::cout << "Sum: " << sum << std::endl;
std::cout << "Average: " << (float)sum / n << std::endl;
std::cout << "Min: " << min << std::endl;
std::cout << "Max: " << max << std::endl;
}
int main()
{
int numberCount;
do
{
std::cout << "How many numbers would you like to print? ";
std::cin >> numberCount;
}while(numberCount <= 0);
printStatistics(numberCount);
}