所以我想写一个有关约旦支付账单和东西的故事。我使用了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]

最佳答案

(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;

09-04 17:25