该函数的输出应该是双倍的,但它给了我整数

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

我制作了一个程序,它实际上很好用,里面有一个用户定义的函数,但只有一个问题,如标题所示,我得到的是整数输出而不是双精度,我不知道为什么我尝试了我所知道的一切但最终失败了。

为什么函数的结果是整数而不是双精度数?

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.

这是我的程序代码:

#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;
}

您只需调用 srand(time(0)); 一次,您将得到双重结果。

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

srand(time(0)); 移动到循环之前。

使用 srand(time(0)); 时,您在每个循环中重新初始化随机数生成器,这会导致在 for 循环的每次迭代中调用 rand() 产生相同的结果,因此将相同的数字添加到 sum howManyNumbers 次。

因此,当除以 howManyNumbers 时,它会返回一个 "whole" 整数(或足够接近,以致于使用的精度不会显示错误)。

简单;

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

Demo