Originally Posted by
bithub
You probably want the average as a floating point variable.
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=(static_cast<float>(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;
return 0;
}
I changed it to
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;
}
but there is no difference.