Tuesday, July 28, 2009

C++ Loops can anyone help?

Hello,


I have to create a program in C++ for school and I cannot figure out how to make it work. Any help is appriciated. These are the requirments:





Write a program that will average a set number of bolwing scores. Ask the user how many games were played. The user will enter that number of games, the scores for those games and then the program will calcuate the average to the nearest tenth. If the user enters a non-positive number for the number of games to be entered, re-ask for the number of games(use a do-while loop). User a for loop to allow the use to enter all the scores.





~GR3

C++ Loops can anyone help?
The correct code is as follows:





#include %26lt;cstdlib%26gt;


#include %26lt;iostream%26gt;





using namespace std;





int main(int argc, char *argv[])


{


int games;


double scores;


double sum;


double average;





do


{





cout%26lt;%26lt;"How many games did you bowl? ";


cin%26gt;%26gt;games;


}while(games%26lt;=0)


sum = 0; // %26lt;-- This line is very important because if you do not initialize the running total to zero, you will get a random result for your running total.


for(i=1; i%26lt;=games ; i++)


{


cout%26lt;%26lt;"Please enter the scores of your games: ";


cin%26gt;%26gt;scores;


sum = sum + scores; // %26lt;-- This is where you add the scores to the running total.


}


cout%26lt;%26lt;fixed;


cout%26lt;%26lt;setprecision(1);


average = sum / games;


cout%26lt;%26lt;"The average of all of your games is "%26lt;%26lt;average%26lt;%26lt;endl;


system("PAUSE");


return EXIT_SUCCESS;


}





Hope this helps


Daz
Reply:Your program is nearly right just a few changes in for loop just add


sum+=scores;


and when initalizing use


double sum =0;


and remove the line


sum = sum + games;
Reply:well to use the for loop do this





ask the user for the number of scores their going to enter and output that to a variable (say x) then you would use the for loop kinda like this (im a bit rusty on c++)





for(int j%26lt;x, j++)


{


cin%26gt;%26gt;s;


score=score+s


}


This should generate a loop and you would insert the code here to ask for each score


then out of that loop you would calculate the average based on the variable x





avg=score/x





for the do while try this





while(x%26gt;=0)


{


previous code stated


}


No comments:

Post a Comment