C#应用程序充当Magic 8球 [英] C# Application to act as a Magic 8 ball
问题描述
你好,
该网站的新手和C#在一起.
我想知道如何制作Magic 8球的业余版本.
我需要提供的所有帮助是:如何生成随机的是和否答案?
用户将输入一个随机问题,那么我希望应用程序给出一个随机的是和否.
非常感谢您的帮助!
-G
Hello,
New to this site and C# all together.
I was wondering how I could build a amateur version of a Magic 8 ball.
All I need help on is this: How do I generate a random yes and no answer?
The user would input a random question and well I want the application to give a random yes and no.
Thank you very much for the help!
-G
推荐答案
Random rnd = new Random();
if((rnd.Next() & 1) == 0)
{
// Yes ...
}
else
{
// No
}
这通过检查是否未设置最低位(整数为偶数)来工作,但您也可以检查是否设置了位(== 1,等于奇数).
另一种可行的方法是%(取模运算符),它给出余数.
x%n给出x除以n的余数:例如X = 6 N = 3
6%3 == 0
如果您需要两个以上的是"和否"选项,这将非常有用.
例如:
0 ==是"
1 ==否"
2 ==稍后再问"
3 ==不太可能"
This works by checking if the lowest bit is not set (integer is even) but you could also check if bit is set ( == 1 which amounts to odd).
Another way to go is % (modulo operator) which gives the remainder.
x % n gives the remainder of the division of x by n: e.g X = 6 N = 3
6 % 3 == 0
This is very usefull if you need more than the 2 options "yes" and "no".
For example:
0 == "Yes"
1 == "No"
2 == "Ask again later"
3 == "Not very likely"
int numberOfChoices = 4;
Random rnd = new Random();
switch(rnd % numberOfChoices)
{
case 0:
//"Yes" stuff goes here
break;
case 1:
//"No" stuff goes here
break;
case 2:
//"Ask again later" stuff goes here
break;
case 3:
//"Not very likely" stuff goes here
break;
}
干杯
Manfred
Cheers
Manfred
Google is your friend
You should always start with a simple search on google because most beginner questions will already have answers out there.
Cheers
Random rand = new Random();
int i = rand.Next(2); // generates numbers between 0 and 1
string strYesOrNo = (i == 0) ? "yes" : "no";
这篇关于C#应用程序充当Magic 8球的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!