簡體   English   中英

C++ 中的 rand() function 給出的數字超出了范圍

[英]The rand() function in C++ is giving a number outside the range

所以我想寫一個關於喬丹支付賬單之類的故事。 我使用 rand function 為他的工資 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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM