【问题标题】:Random Number Generation in C# errors outC# 中的随机数生成错误
【发布时间】:2019-02-12 07:21:02
【问题描述】:

所以我正在尝试生成一个 随机数,如果该数字是 38 我会发生什么事情,这种情况是 add @ 987654323@ 到 2 个整数之一

请记住,我真的只是在阅读 C# 书籍和一些 VB 知识

    int Number1 = 0;
    int Number12 = 0;
    string text;
    string text2;

    Exexs:

    Random rnd = new Random();
    int month = rnd.Next(1, 10);

    if (month = 8)
    {
        Number1++;
    }
    else if (month = 3)
    {
        Number12++;
    }

    if (Number1 = 1)
    {
        text = "*";
    }

    goto Exexs;

【问题讨论】:

  • First of:: 从来没有使用goto。它使您的代码难以阅读和调试。除此之外,您应该阅读一些关于 C# 的书,或者至少阅读一些教程。
  • 您在 if 条件中缺少 '=='。例如 if(month = 8) 需要为 ifImonth==8)
  • 不要重新创建Random - Random rnd = new Random(); - 这样做一次然后使用它
  • 虽然很明显但是你为什么不提到你的代码的确切错误?
  • 您如何知道运行此代码的结果是什么?它什么也不输出,永远运行......一个无限循环!

标签: c# if-statement random numbers


【解决方案1】:

您的代码中有太多错误;看来,实现应该是这样的:

int Number1 = 0;
int Number12 = 0;
// Do not forget to initialize the varaiables:
string text = "";
string text2 = "";

// Create (and initialize by system tomer) Random once, use many
Random rnd = new Random();

// Do not use goto, but loops (they are more readable: we have an infinite loop here)
while (true) {
  int month = rnd.Next(1, 10);

  // (month = 8) is an assignment, not comparison which is (month == 8)
  // Let's use C/C++ language trick: comparing in reversed order: 
  // (8 == month) and you can easily find out such errors
  if (8 == month)
    Number1++;
  else if (3 == month)
    Number12++;

  if (1 == Number1) {
    text = "*";

    // you want to leave the infinite loop (your current code never stops)
    break; 
  }
}

// Let's inspect the outcome
Console.Write($"Number1 = {Number1}; Number12 = {Number12} Text = {text}"); 

【讨论】:

    【解决方案2】:

    在c#中为了比较你需要使用双= 所以,而不是:

    if (month = 8)
    

    类型:

    if (month == 8)
    

    【讨论】:

    • 感谢所有我修复它的人,错误是关于 int 不是 bool
    • @Kernel 使这个问题无法回答,因为它缺少所有相关信息。
    猜你喜欢
    • 2016-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-02
    • 2010-11-29
    • 1970-01-01
    • 1970-01-01
    • 2011-05-05
    相关资源
    最近更新 更多