c++ primer plus 第六版 12章的第五题,我用循环来做发现用来计算排队总时间的long值会变成负数


#include <cstdlib>     
#include <ctime>        
#include "Stack.h"
#include<iostream>
const int per = 60;
bool newcustomer(double x);
int main()
{
    using namespace std;
    srand(time(0));
    cout << "输入队列的最大人数:\n";
    int qs;
    cin >> qs;
    Queue line(qs);
    cout << "输入实验的总时间(小时):\n";
    int hours;
    cin >> hours;
    long limit = hours * per;
    for (int i = 29; i <= 30; i++)
    {
        double between;
        between = (double)per / i;
        Item temp;
        long turnaways = 0;
        long customers = 0;
        long wait_time = 0;
        long served = 0;
         long line_wait = 0l;
         for (int cycle = 0; cycle < limit; cycle++)
         {
             if (wait_time > 0) wait_time--;
             if ((newcustomer(between)))
             {
                 customers++;
                 if (line.isfull()) turnaways++;
                 else
                 {
                     temp.set(cycle);
                     line.enqueue(temp);
                 }
             }
             if (wait_time <= 0 && line.isempty() == false)
             {
                 line.dequeue(temp);
                 served++;
                 wait_time = temp.ptime();
                 line_wait += (cycle - temp.when());
             }
         }
        if ((double)line_wait / served <= 1.0)
        {
            cout << "当每小时到的客户有" << i << "人时,平均等候时间为" << (double)line_wait / served << endl;
            cout << "此时服务总客户数为: " << served << endl;
            cout << "总等候时间为: " << line_wait << endl;
        }
    }
}
bool newcustomer(double x)
{
    return (rand() * x / RAND_MAX < 1);
}


最后运行的结果中会出现这样的问题:

img


#include<bits/stdc++.h>
using namespace std;
struct st
{
    int num;
    int t;
}a[1010];
bool cmp(st x,st y)
{
    if(x.t!=y.t) return x.t<y.t;
    else return x.num<y.num;
}
int main()
{
    int n;
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        cin>>a[i].t;
        a[i].num=i;
    }
    sort(a+1,a+n+1,cmp);
    double sum=0.0,s=a[1].t;
    cout<<a[1].num;
    for(int i=2;i<=n;i++)
    {
        cout<<" "<<a[i].num;
        sum+=s;
        s+=a[i].t;
    }
    cout<<endl;
    cout<<setprecision(2)<<fixed<<1.0*sum/n;
}

这样看看?