0

As the code stands now, the sentinel is being included in the calculation for the average. Any pointers on how to break the loop without including the sentinel?

#include <iostream>
using namespace std;
int main ()
{

int fahr=0,cent=0,count=0,fav=0;

while (fahr!=-9999)
{
    count ++;       
    cout<<"Input the fahrenheit temp to be converted to centigrade or enter -9999 "<<endl;
    cin>>fahr;
    cent=(float)(5./9.)*(fahr-32);
    cout<<"The inputed fahr "<<fahr<<endl;  
    cout<<"The cent equivalent "<<cent<<endl;



}
fav=(float)(fav+fahr)/count;
    cout<<"Average"<<fav<<endl;
return 0;

}   
Sam Dufel
  • 17,560
  • 3
  • 48
  • 51
zeheroe
  • 13
  • 4
  • Your code isn't calculating an average. You'd need some accumulator like `total += fahr` each loop. Then your average should be `total / count`. Also, there's no need to cast the total to `float` if the result is stored as an `int`. You'll end up with the same result as integer division anyway. – japreiss Feb 09 '12 at 05:26

2 Answers2

1

Make the code run in an infinite loop, and use break to terminate the loop if you see -9999.

#include <iostream>
using namespace std;
int main ()
{

int fahr=0,cent=0,count=0,fav=0;

while (true)
{
    count ++;       
    cout<<"Input the fahrenheit temp to be converted to centigrade or enter -9999 "<<endl;
    cin>>fahr;

    if (fahr == -9999)
       break;

    cent=(float)(5./9.)*(fahr-32);
    cout<<"The inputed fahr "<<fahr<<endl;  
    cout<<"The cent equivalent "<<cent<<endl;
}

fav=(float)(fav+fahr)/count;
cout<<"Average"<<fav<<endl;
return 0;

} 
Oleksi
  • 12,947
  • 4
  • 56
  • 80
0

Probably you need to add one more line after

cout<<"The cent equivalent "<<cent<<endl;

add:

fav += cent;

and change

fav=(float)(fav+fahr)/count;

to:

fav=(float)fav/count;