gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 04:09:18 24 4
gpt4 key购买 nike

所以我想写一个关于乔丹支付账单之类的故事。我使用随机函数为他的薪水 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;

关于c++ - C++ 中的 rand() 函数给出了超出范围的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58152682/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com