c#投掷骰子的方法

本文关键字:方法 掷骰子 | 更新日期: 2023-09-27 18:17:18

我需要两个方法。第一个方法投掷四个骰子并返回骰子的和。第二种方法估计总和,如果总和大于20,则打印"优秀",如果总和大于12或总和小于或等于20,则打印"良好",如果总和小于或等于12,则打印"差"。

通过写行来掷骰子

Random ran = new Random ();
int throwingdice = ran.nextInt(1,7);

我试了很多次,但它不会工作,有什么想法吗?

c#投掷骰子的方法

这应该可以帮助你开始…

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Random r = new Random();
            int sum=0;
            for (int i = 0; i < 4; i++)
            {
                var roll = r.Next(1, 7);
                sum += roll;
            }
            // sum should be the sum of the four dices
            Console.WriteLine("the sum of the first 4 throws is {0}", sum);
            if (sum > 20)
            {
                Console.WriteLine("place your message in here stating that sum gas greater than 20");
            }
            else if (sum < 10)
            {
                Console.WriteLine("sum is less than 10");
            }
            else
            {
                Console.WriteLine("some other message");
            }
        }
    }
}

那么当你想要的一切都可以在一个方法中实现时第二个方法的目的是什么呢正如Tono Nam所示。您可以简单地添加一个switch语句或if else块来输出您的字符串值。

public void yourMethod()
{
    Random r = new Random(); 
    int sum=0;       
    for (int i = 0; i < 4; i++)         
    {             
        var roll = r.Next(1, 7);             
        sum += roll;         
    }         // sum should be the sum of the four dices 

    //a switch is faster for a larger amount of options
    switch(sum)
    {
        case 20:
        {
            Console.WriteLine("excellent");
        }
    }
    //Or use If else
    if(sum>=20)
    {
        Console.WriteLine("excellent");
    }
}

只是一个例子,需要建立

  1. 你应该重命名你的变量"throw",因为throw在c#中有特殊的含义,如for,each,int等。

  2. 这里有一个使用random()的例子:

    using System;
    using System.Threading;
    public class RandomNumbers
    {
        public static void Main()
        {
           Random rand1 = new Random();
           Random rand2 = new Random();
           Thread.Sleep(2000);
           Random rand3 = new Random();
           ShowRandomNumbers(rand1);
           ShowRandomNumbers(rand2);
           ShowRandomNumbers(rand3);
        }
        private static void ShowRandomNumbers(Random rand)
        {
          Console.WriteLine();
          byte[] values = new byte[5];
          rand.NextBytes(values);
          foreach (byte value in values)
             Console.Write("{0, 5}", value);
          Console.WriteLine();   
        }
    }
    // The example displays the following output to the console:
    //       28   35  133  224   58
    //    
    //       28   35  133  224   58
    //    
    //       32  222   43  251   49
    

    来源:http://msdn.microsoft.com/de-de/library/h343ddh9.aspx