数组在函数混乱C++



我需要编写一个程序,该程序传递一个 int 数组及其大小,并打印出高于平均水平的数字。谁能帮我澄清这个问题?我坐在这里想知道它到底在问什么,而且我对编程还很陌生,所以我不知道该怎么办。 对不起,我听起来很不能,但我只是很困惑。感谢任何可以提供帮助的人。这就是我到目前为止所拥有的一切:

这是更新的代码,但我仍然无法弄清楚为什么没有显示多个平均值,或者如何使输出值正确。
编辑:将 average() 函数中的几个 int 值更改为浮点数,但最后的总值仍然存在问题

#include <iostream>
using namespace std;
int average(int values[],int size);
int main(){
int size;
int values[] = {1,2,3,4,5,6};
cout << "Please input the size of the array" << endl;
cin >> size;
int output = average(values, size);
if(values[size]>output){
    cout << "The values above average are: " << output << endl;
}
return 0;
}
int average(int values[],int size){
float temp=0.0;
for(int i=0;i<size;i++){
    temp += values[i];
}
float end=temp/size;
return end;
}

你应该创建一个intigers数组并将其传递给平均函数,并且需要传递大小(以便你知道循环多少次)。在 Average 函数的循环中,将所有值添加到一个临时值,然后除以输入到函数的计数。

//returns the average
int average(int Values[],int Size){
    //perhaps declare a temporary value here
    for(int i=0;i<Size;i++){
        //add all the values up and store in a temporary value
    }
    //here divide by Size and return that as the average
}

if(values[size]>output){
    cout << "The values above average are: " << output << endl;
}

应替换为以下内容:

for(int i=0;i<size;i++){
    if(values[i]>output){
        cout << "The values above average are: " << values[i] << endl;
    }
}

这是一个比发布的解决方案更不复杂的解决方案。主要功能:它实际上确实做了它应该做的事情:

#include <iostream>
template<size_t N>
float average( const int (&value)[N] ) {
    float total( 0.0f );
    // Sum all values
    for ( size_t index = 0; index < N; ++index )
        total += value[index];
    // And divide by the number of items
    return ( total / N );
}
int main() {
    int value[]  = { 1, 2, 3, 4, 5, 6 };
    // Calculate average value
    float avg = average( value );
    const size_t count = ( sizeof( value ) / sizeof( value[0] ) );
    // Iterate over all values...
    for ( size_t index = 0; index < count; ++index )
        // ... and print those above average
        if ( value[index] > avg )
            std::cout << value[index] << std::endl;
    return 0;
}

Ideone的活生生的例子。输出:

4
5
6

最新更新