I've recently started learning programming at university and I've been asked to write a C++ program for the following problem:
"The program will keep asking the user to enter a pair of integers,
start and
finish, and will terminate whenever
start>
finish, or EOF or an invalid input is encountered. Every time a new pair of integers are read, the program will first calculate the
subtotal and then add the
subtotal to the
total. Before the program terminates, it should display the accumulated
total and the
average of all the
subtotals."
That seemed easy to me at first, but an example was added at the end showing how the subtotals should be calculated:
"
start2+(
start+1)
2+(
start+2)
2+ ... +(
finish-1)
2+
finish2
eg. If you enter
3 for
start and
8 for
finish, then the formula for the subtotal becomes:
3
2 + 4
2 + 5
2 + 6
2 + 7
2 + 8
2"
My first attempt seemed promising to begin with, but it isn't producing the expected output. I'm not too sure if my combination of
while and
for loops is appropriate for this task and lines 18 and 19 seem to be a problem because the
total displayed at the end is far larger than it should be.
I've omitted attempts at working out the
average until I've figured out the
total. I'm not even sure where to start for working out the
average.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
#include <iostream>
using namespace std;
int main ()
{
int start, finish, squared, total = 0, subtotal = 0;
float average;
cout << "Enter Start as integer: ";
cin >> start;
cout << "Enter Finish as integer: ";
cin >> finish;
while(start <= finish)
{
for(start; start <= finish; start++)
{
squared = start * start;//I'm thinking this line and the following line are the main problem
subtotal = subtotal + squared;
}
total = total + subtotal;
cout << "Enter Start as integer: ";
cin >> start;
cout << "Enter Finish as integer: ";
cin >> finish;
}
cout << "TOTAL = " << total << endl;
cout << "AVERAGE = "; //I've left this blank because I'm not entirely sure about the average just yet
return 0;
}
|
Any help would be greatly appreciated.