The output of the function should be double but it gives me integer

I made a program which is actually good and working and it has a user defined function in it but there is only one problem as it's shown in the title, I got integer output instead of double, I don't know why and I tried everything I know but ended up failing.

Why is the result of the function a whole integer and not a double?

Write a function main() that prompts the user to enter three integers number, lower, and upper then calls the function average(): double average( int howManyNumbers, int lower, int upper) which generates howManyNumbers random integers in the range lower and upper inclusive. The function then finds and returns the average of the randomly generated integers. The function should generate different set of values for each run.

And this is my program's code:

#include<iostream>
#include<cstdlib>
#include<ctime>
#include<iomanip>
using namespace std;

int main ()
{
    int number,lower,upper;
    double average (int , int , int);
    cout<<"Enter number, lower, upper: ";
    cin>>number>>lower>>upper;
    cout<<showpoint<<fixed;
    cout<<"The average of the "<<number<<" random integers is"<<average(number,lower,upper );
    return 0;
}

double average (int howManyNumbers, int lower, int upper)
{
    int i;
    double avg,sum=0;
    for (i=0;i<howManyNumbers;i++)
        {
            srand(time(0));
            sum=sum+(lower+rand()%(upper-lower+1));
        }

    avg=(sum/howManyNumbers);
    return avg;
}

Answers


Move the srand(time(0)); to before the loop.

With srand(time(0)); you re-initialise the random number generator on each loop and this results in the same result from the call to rand() in each iteration of the for loop, thus adding the same number to the sum howManyNumbers number of times.

Hence when divided by howManyNumbers, it gives a "whole" integer back (or near enough that the error is not displayed given the precision used).

Simply;

srand(time(0)); // moved to before the loop.
for (i=0;i<howManyNumbers;i++)
{
  // ...
}

Demo


you have to call srand(time(0)); only one time and you will get a double result.

 srand(time(0));
 for (i=0;i<howManyNumbers;i++)
 {
     sum=sum+(lower+rand()%(upper-lower+1));
 }

Need Your Help

"Access denied for user 'root'@'localhost'" on a fresh install of MySQL 5.6.15 on Windows after uninstalling an older version of MySQL

mysql passwords root

So, I've just installed MySQL 5.6.15 on my Windows machine, but for some reason I can't log in using "root" with no password.

Select cell greater than and lesser than some dynamic values

javascript jquery html-table

I want to select cells which is greater than a and lesser than b, where a and b are values of some input box.