samedi 28 septembre 2019

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

So I'm trying to write a story about Jordan paying bills and stuff. I used a rand function to find a random number for his salary 3.5k - 4.5 and bills 700 -1.5k. I believe I got the formula right but usually, it generates a number outside that area. Below is the code and result.

{
    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";
}

I expect Jordan's bills to be around 700-1.5k and his salary 3.5k-4.5k but it gives me a number below that.


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]



Aucun commentaire:

Enregistrer un commentaire