Also, your average is being computed wrong. Shouldn't the average be computed more like:
(pseudo code)
average = sum / (second_number - first_number)
Where second_number - first_number is the difference between the two numbers the user entered.
Printable View
Also, your average is being computed wrong. Shouldn't the average be computed more like:
(pseudo code)
average = sum / (second_number - first_number)
Where second_number - first_number is the difference between the two numbers the user entered.
I changed it to
but there is no difference.Code:#include <iostream>
using namespace std;
int main (){
int num, num1;
float average;
cout<<"Please enter a number\n";
cin>>num;
cout <<"Please enter the number to whcih you want to count\n";
cin>>num1;
int sum = 0;
for (; num<=num1; num++)
{
cout << num << endl;
sum = sum +num; // this is fine and all is OK
}
average=((sum)/(num+1));//but here is the problem. Try with 1 and 12 and you get
// the sum of all numbers from 1 to 12 i.e. 78 but you get the average as 5!
cout<<sum<<average;
cin>>sum;
return 0;
}
What if the user enters the numbers 5 and 12? Then you want to compute the average as sum / (12-5). That is why you can't just use num1.
it should really be
sum/(num1 - num +1)
as you are including the boundary numbers
EDIT: or you could do:
Code:int count = 0;
for (; num<=num1; num++)
{
cout << num << endl;
sum = sum +num; // this is fine and all is OK
count ++;
}
average=((sum)/(count));
Yeah you are right, thanks. I am so thick, only thinking in one way.
Now another question. What if there was no array? I tried to calculate using the sum using the loop alone without an array but I can't figure out how other than using the formula.
There is no array in your code. An array looks like this:
numbers[index]
Can you elaborate please? What do you mean by array?