Sunday, August 2, 2009

In C++, how do you figure out an average using a "for" loop?

I need to create a program which allows the user to enter how many numbers they wish to average, and then prompts them to enter that many numbers. Then, it will take those numbers and average them. Any help?





Here's my code so far:





#include %26lt;iostream.h%26gt;


#include %26lt;conio.h%26gt;


#include %26lt;stdlib.h%26gt;


#include %26lt;dos.h%26gt;





int main()


{ clrscr();


int i;


int a;


cout%26lt;%26lt;"Hello there! Please enter how many numbers you want to average!: ";


cin%26gt;%26gt;a;


clrscr();


int average;


int B;


int sum;


for (i=0; i%26lt;=a-1; i++)


{


cout%26lt;%26lt;"Enter number:\n";


cin%26gt;%26gt;B;


sum=0;


average=sum+i+B/a;


}


cout%26lt;%26lt;"Hit any key to continue...\n\n";


getch();


cout %26lt;%26lt; "Your average = "%26lt;%26lt;average%26lt;%26lt;" ";


getch();





return 0;





}

In C++, how do you figure out an average using a "for" loop?
What the crap do you think you're calculating here???





   sum=0;


   average=sum+i+B/a;





Sum is always zero, so it doesn't add anything... Also, you calculate an average by summing all the numbers AND counting them, and only divide the sum by the number at the end...
Reply:here you go. the modified program.





#include %26lt;iostream.h%26gt;


#include %26lt;conio.h%26gt;


#include %26lt;stdlib.h%26gt;


#include %26lt;dos.h%26gt;





int main()


{ clrscr();


int i;


int a;


cout%26lt;%26lt;"Hello there! Please enter how many numbers you want to average!: ";


cin%26gt;%26gt;a;


clrscr();


int average;


int B;


int sum=0;


for (i=0; i%26lt;=a-1; i++)


{


cout%26lt;%26lt;"Enter number:\n";


cin%26gt;%26gt;B;


sum+=B;


}


average=sum/a;


cout%26lt;%26lt;"Hit any key to continue...\n\n";


getch();


cout %26lt;%26lt; "Your average = "%26lt;%26lt;average%26lt;%26lt;" ";


getch();





return 0;





}


No comments:

Post a Comment