for loop problem

Hello everyone! I wrote a program that asks the user to enter a number. Then it asks the user if they would like to enter another number. If yes, press y. If the user enters n (no), the loop immediatly stops. The program then tells me how many numbers the user has entered, the sum of the numbers entered, the average of the numbers entered, the smallest number entered, and largest number entered. Here's the problem: it's giving me the wrong numbers! Otherwise, everything in the program before the for loop is working.

Perhaps, my math is wrong or I need to put something in the while loops, but it is frustrating. Any advice or tips would be greatly appreciated! Thanks guys!



#include <iostream>
#include <conio.h>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
int main ()
{
int number;
char c;
int y, n;
int howmany = 1;
int count = 1;
int sum = 0;
double average;
long long int smallest = 1000000;
long long int largest = 0;

cout << "Enter a number: ";
cin >> number;
cout << "Would you like to enter another number (y or n)? ";
cin >> c;

while (c == 'y')
{
cout << "Enter a number: ";
cin >> number;

if (number < 0 || number > 100)
{
cout << "The number must be in the range 0 to 100. " << endl;
cout << "Enter a number: ";
cin >> number;
}

if (number >= 0 || number <=100)
{
cout << "Would you like to enter another number (y or n)? ";
cin >> c;
}

if (c == 'n');

howmany++;
}

if (c == 'n')
{
cout << "You have entered " << howmany << " number(s)" << endl;
}

for (count = 1; count <= howmany; count++)
{
sum = sum + number;

if (number > largest)
largest = number;

if (number < smallest)
smallest = number;
}

average = double (sum) / howmany;

cout.precision(2);
cout.setf(ios::showpoint);
cout.setf(ios::fixed);

cout << "The sum is " << sum << endl;
cout << "The average is " << average << endl;
cout << "The largest is " << largest << endl;
cout << "The smallest is " << smallest << endl;

getch();
return 0;
}
Sorry, the code isn't lined up correctly.
You are asking one time before the loop and then again within the loop and THEN you are making the calculations. You should only ask once per every loop.

Replace this ouside the loop
1
2
3
4
cout << "Enter a number: ";
cin >> number;
cout << "Would you like to enter another number (y or n)? ";
cin >> c;


for this:
 
c = 'y';

Topic archived. No new replies allowed.