我的情况是我必须生成一个随机数,这个数字必须是zero
或one
所以,代码是这样的:
randomNumber = new Random().Next(0,1)
但是,业务要求规定生成的数字为零的可能性仅为10%,生成的数字为1的概率为90%
但是,我可以在生成随机数时包含这个概率吗?
但是我不知道这种方式是否正确,另外,我认为C#应该有一些准备好的东西
答案 0 :(得分:5)
以10%的概率获得:
bool result = new Random().Next(1, 11) % 10 == 0;
以40%的概率获得真实:
bool result = new Random().Next(1, 11) > 6;
答案 1 :(得分:5)
您可以这样实现:
faultType: <Fault senv:Client.SchemaValidationError: :10:0:ERROR:SCHEMASV:SCHEMAV_CVC_ELT_1: Element 'testMethod': No matching global declaration available for the validation root.>
************************************************************************
*** Outgoing SOAP ******************************************************
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/1999/XMLSchema"
>
<SOAP-ENV:Body>
<testMethod SOAP-ENC:root="1">
<name xsi:type="xsd:string">john</name>
</testMethod>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
*** Incoming SOAP ******************************************************
<?xml version='1.0' encoding='UTF-8'?>
<senv:Envelope xmlns:senv="http://schemas.xmlsoap.org/soap/envelope /"><senv:Body><senv:Fault> <faultcode>senv:Client.SchemaValidationError</faultcode> <faultstring>:10:0:ERROR:SCHEMASV:SCHEMAV_CVC_ELT_1: Element 'testMethod': No matching global declaration available for the validation root.</faultstring><faultactor></faultactor></senv:Fault></senv:Body></senv:Envelope>
答案 2 :(得分:2)
首先,您应该保存对随机实例的引用,以便获得正确的随机数字序列:
Random randGen = new Random();
要知道的第二件事是,随机的最大值是独占的,所以要妥善解决你应该做的问题:
int eitherOneOrZero = randGen.Next(1, 11) % 10;
要将其概括为任何机会变化,您可以这样做:
Random randGen = new Random();
var trueChance = 60;
int x = randGen.Next(0, 100) < trueChance ? 1 : 0;
<强>测试强>
Random randGen = new Random();
var trueChance = 60;
var totalCount = 1000;
var trueCount = 0;
var falseCount = 0;
for (int i = 0; i < totalCount; i++)
{
int x = randGen.Next(0, 100) < trueChance ? 1 : 0;
if (x == 1)
{
trueCount++;
}
else
{
falseCount++;
}
}
<强>输出:强>
正确:60.30%
错误:39.70%