Reputation: 107
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
Reputation: 83
Steps:
Upvotes: 0
Reputation: 9908
int d;
if you are taking d
as input before it use for first time.d
taken as input. Now declare the int Temperature[d];
so that if the total number of observation exceed 100 it should work.d-1
.for()
loop doesn't have;
at the end.Upvotes: 0
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
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