数组减去平均值放入另一个数组?

时间:2014-11-19 21:31:07

标签: c++

我不知道如何启动此功能。

我希望数组中的值从平均值中减去以生成新数组。

示例:

1 2 3 old array
avg 2
new array -1 0 1

之前有一个程序,由于错误而无法运行它。

任何人都可以给我一个提示吗?

#include <iostream>
#include <cmath>

using namespace std;

const int SIZE = 100;
void readdata (double [], int &);
double findaverage (double [], int);
void howfaraway (double [], int);

int main()
{
    int n;
    double avg;
    double mark[SIZE];

    readdata(mark, n);
    avg = findaverage(mark, n);
    cout << avg;
    return 0;
}

void readdata(double numbers[], int&n)
{
    cout << "Enter the size> ";
    cin >> n;
    for (int count = 0; count < n; count++)
    {
        cout << "Enter the integer> ";
        cin >> numbers[count];
    }
    return;
}

double findaverage (double p[], int n)
{
    double sum = 0;
    for (int count = 0; count < n; count++)
        sum = sum + p[count];

    return (double) sum / n;
}

void howfaraway (double r[], double s[], int n)
{
    for (int count = 0; count < n; count++)

}

2 个答案:

答案 0 :(得分:1)

&#39;我会写一些伪代码:

length = lengthOf(oldarray);
newarray = new array[length]
avg=sum(oldarray)/length;


for(i=0; i<length; i++){
    newarray[i]=oldarray[i]-avg;
}

return newarray;

类似的东西。

答案 1 :(得分:1)

我在你的代码中改写了一些东西。我希望这有帮助:

#include <iostream>
#include <cmath>

using namespace std;
const int SIZE = 100;

//Variables here
int n;
double avg, numbers[SIZE];

//Functions here
void readdata ();
double findaverage ();
void howfaraway ();

int main()
{
    readdata(); // Read the input and calculate the avg.
    cout << "This is the Average: " << avg << endl; // Printing the avg
    cout << "This is the new array: "; 
    howfaraway(); // Printing the new array
    return 0;
}

void readdata()
{
    cout << "Enter the size: ";
    cin >> n;
    avg = 0;
    for (int i = 0; i < n; i++)
    {
        cout << "Enter the integer: ";
        cin >> numbers[i];
        avg += numbers[i]; // Getting the total sum
    }
    if(n > 0)
        avg /= n; // Getting the avg
}

void howfaraway()
{
    for (int i = 0; i < n; i++)
        cout << numbers[i] - avg << " "; // Printing each new element
    cout << endl;
} 
相关问题