Shien
Shien

Reputation: 107

How to get average from array

Trying to get some C++ basics but have a problem. I need to get an average value of temperature array values. Posting code in here. I know that I've done something wrong, because I'm getting the wrong answers. Can you please tell me what's wrong?

#include <iostream>
using namespace std;
int main()
{
    int d = 0, i;
    double avg = 0, sum = 0, Temperature[100];
    // -----------------------------------------
    cin >> d;
    for (i = 1; i <= d; i++)        
    {
        cin >> Temperature[i];
    }
    for (i = 1; i <= d; i++)
    {
        cout << Temperature[i] << endl;  // was Temperatura[i] ?
    }
    for (i = 1; i <= d; i++);
    {
        sum += Temperature[i];
    }
    avg= sum / d;
    cout << "Average: " << avg << " Sum: " << sum << endl;

    system("pause");
    return 0;
}

Upvotes: 0

Views: 767

Answers (4)

Cata
Cata

Reputation: 83

Steps:

  1. You declare the Temperatures array, the number of temperatures (you used 'd', but you don't need to initialize it with 0, just read it) and a variable which keeps the sum of Temperatures (ex.: double sum = 0)
  2. In a for loop (for i = 1; i <= d; i++ || for i = 0; i < d; i++) you read the Temperatures and increase the sum with each of the elemens (sum += Temperatures[i] || sum = sum + Temperatures[i]
  3. Output: cout << sum / n; Formula : average = (elem1 + elem2 + ... + elem n) / n

Upvotes: 0

Shravan40
Shravan40

Reputation: 9908

  • You don't need to initialize int d; if you are taking d as input before it use for first time.
  • Once d taken as input. Now declare the int Temperature[d]; so that if the total number of observation exceed 100 it should work.
  • Now iterate the array, for taking input and calculating sum. Note that - Array indices starts from zero instead of one. Goes to d-1.
  • for() loop doesn't have; at the end.

Upvotes: 0

ravi
ravi

Reputation: 10733

The problem is a result of silly mistake:-

for (i = 1; i <= d; i++);  << semicolon

Remove semicolon from end of for loop.

Upvotes: 3

Patato
Patato

Reputation: 1472

Maybe it because the input number d is larger than 100

#include <iostream>
using namespace std;
int main()
{
    int d = 0, i;
    double avg = 0, sum = 0, *Temperature=0;
    // -----------------------------------------
    cin >> d;
    Temperature=new  double[d];  //<== Use new to allocate array

    for (i = 0; i < d; i++)     //<== Normaly array start at 0       
    {
        cin >> Temperature[i];
    }
    for (i = 0; i < d; i++)
    {
        cout << Temperatura[i] <<endl;
    }
    for (i = 0; i < d; i++);
    {
        sum += Temperature[i];
    }
    average = sum / d;
    cout << "Average: " << avg << " Sum: " << sum << endl;
    if(Temperature!=0)              //<== Free  memory
    {
      delete []Temperature;
    }
    system("pause");
    return 0;
}

Upvotes: 0

Related Questions