mean average program

I have a program that computes the mean average for positive integers up to the number the user inputs. I need to be able to specify what two positive numbers I want to compute the mean average of. Here is the code using a for loop to find the average when the user inputs a number.

#include "stdafx.h"
#include <iostream>
using namespace std;

int main()
{
int value; // value is some positive number n
int total = 0; // total holds the sum on the first n positive numbers
int number; // the amount of numbers
float mean; // the average of the first n positive numbers

cout << "Please enter a positive number" << endl;
cin >> value;

if (value > 0)
{
for (number = 1; number <= value; number++)
{
total = total + number;
}
mean = static_cast<float>(total) / value;
cout << "The mean average of the first " << value
<< " positive integers is " << mean << endl;
}

else
{
cout << "Invalid input - integer must be positive" << endl;
}
return 0;
}
does it work, did you have a question?

some unimportant thoughts...
- this problem can be solved directly, without the loop, it is a simple formula.
- total+= number instead of total= total+number is slightly cleaner looking (no harm here)
- floats have a very low resolution, always use doubles.
Thanks for answering. I need to make the program accept two positive numbers from the user. Then it must add all the numbers in between those two numbers together and find an average. So if the user enters lets say 2 and 4 the program should add 2 + 3 + 4 and then divide by 3 to find the mean average
oh, I see.
you just need to
int start;
cin >> start; //add same logic to ensure >= 0 or >0 depending on your wants (strictly, 0 isnt positive, but it has a drastic effects on averages so it matters)
and then change the for loop
for(i = start; i <= value; i++)

you also want to either force start < value OR reverse them if not, else the for loop will be skipped (that is for (i = 10, i <= 5; i++) will never enter the loop body)
Last edited on
Thanks for your help I'll give that a try after work.
Topic archived. No new replies allowed.