C ++中的rand()函数给出的数字超出范围

问题描述 投票:0回答:1

所以我想写一个有关约旦支付账单和东西的故事。我使用了一个rand函数为他的薪水3.5k-4.5和账单700 -1.5k找到一个随机数。我相信公式是正确的,但通常情况下,它会在该区域之外生成一个数字。下面是代码和结果。

{
    srand(time(NULL));  
    cout << fixed;
    cout << setprecision(2);
    float money = 9000;
    int minbill = 700;
    int maxbill = 1500;
    int minsal = 3500;
    int maxsal = 4500;
    float rent = 3000;

    cout << "[Jordan's Balance: Gp" << money << "]\n\n";
    cout << "Jordan's rent costs Gp" << rent <<".\n";
    float bill = (rand()%maxbill-minbill+1)+minbill;
    cout << "Jordan's bills costs Gp" << bill << ".\n";
    float totalb = rent + bill;
    cout << "Jordan needs to pay a total of Gp" << totalb << "\n\n";
    float sal = (rand()%maxsal-minsal+1)+minsal;
    cout << "Jordan received a salary of Gp" << sal << "!!\n";
    money = money + sal;
    cout << "[Jordan's Balance: Gp" << money << "]\n\n";
}

我希望乔丹的账单在700-1.5k左右,而他的薪水在3.5k-4.5k,但这给了我一个低于这个数字。


Jordan's rent costs Gp3000.00.
Jordan's bills costs Gp133.00.
Jordan needs to pay a total of Gp3133.00

Jordan received a salary of Gp1906.00!!
[Jordan's Balance: Gp10906.00]
c++ random
1个回答
1
投票

[(rand()%maxbill-minbill+1)是错误的。

rand()%maxbill可能小于minbill。您需要使用rand() % (maxbill - minbill + 1)

float bill = rand() % (maxbill-minbill+1) + minbill;

类似地,使用

float sal = rand() % (maxsal-minsal+1) + minsal;
© www.soinside.com 2019 - 2024. All rights reserved.