我有一些代码可以将预先计算的数字发送到 Arduino。 我想要一个数字范围之间的随机数,例如数字1到20之间,随机数是18,而不是预先计算的数字 找到随机数后,将其放入字符串中,以便我可以使用它。
我已经尝试了很多关于堆栈溢出的方法,但是事情太复杂了,而且我使用 C#。 下面的代码是我现在所拥有的, 我希望它将随机数发送到 Arduino
namespace MyLaserTurret
{
public partial class Form1 : Form
{
public Stopwatch watch { get; set; }
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
watch = Stopwatch.StartNew();
port.Open();
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
writeToPort(new Point(e.X, e.Y));
}
public void writeToPort(Point coordinates)
{
if (watch.ElapsedMilliseconds > 15)
{
watch = Stopwatch.StartNew();
port.Write(String.Format("X{0}Y{1}",
(coordinates.X / (Size.Width / 180)),
(coordinates.Y / (Size.Height / 180))));
}
}
}
}
最佳答案
要创建一个随机数作为字符串,请使用此代码
private Random random = new Random();
public string RandomNumber(int min, int max)
{
return random.Next(min, max).ToString();
}
请注意,声明“Random random = new Random();”可能是最佳实践。作为类属性,因为当随机创建的距离太近时,它们将保持相同的值
关于c# - 带字符串的随机数生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56340177/