Datakurser
Aktuell vecka: 48

Tillbaka till toppen

C# Sleep Clear Random

Sleep

Om vi vill få ett program att stanna upp i ett visst läge ett antal millisekunder.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Sleep
{
class Program
{
    static void Main(string[] args)
    {
        int x=1;
        while (x>0)
        {
            Thread.Sleep(x);
            Console.WriteLine("Skriv sovtid (i millisekunder):");
            x=int.Parse(Console.ReadLine());
        }
    }
}
}

int summa( int a, int b) //huvud
{
    return a+b; //kropp
}

 

Clear - rensa skärmen

Om vi vill få console-fönstret rensat.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Clear
{
    class Program
    {
        static void Main(string[] args)
        {
            int x = 10;
            while (x > 0)
            {
                Console.WriteLine(x);
                Thread.Sleep(1000);
                Console.Clear();
                x--;
            }
            Console.WriteLine("BOOOOOOOOOOOOOOOM!");
            Console.ReadKey();
        }
    }
}

Random - Slumptal

Vi har lite inbyggda finesser att bekanta oss med.

Följande skapa ett handtag till en slumptalsserie så används antingen
Random( ) som initieras av datorns klocka eller
Random(tal) där man själv anger ett tal som slumptalsfrö.

Sen använder en metod för att plocka ut slumptalen
Next( ) som ger ett heltal mellan 0 och 2147483647
Next(x) som ger ett heltal mellan 0 och x-1
Next(x,y) som ger ett heltal mellan x och y-1
NextDouble( ) som ger ett decimaltal mellan 0 och 1, 0<=tal<1

Ett exempel

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RandomExempel
{
class Program
{
    static void Main(string[] args)
    {
        int i;
        Random randomTal1 = new Random();
        //Random randomTal2 = new Random(123);
        Console.WriteLine("Next() som ger heltal mellan 0 och 2147483647");
        for (i = 0; i < 10; i++)
            Console.WriteLine(randomTal1.Next());
        Console.WriteLine("\nNext(x) som ger heltal mellan 0 och x-1");
        for (i = 0; i < 10; i++)
            Console.Write(randomTal1.Next(10)+" ");
        Console.WriteLine("\n\nNext(x,y) som ger heltal mellan x och y-1");
        for (i = 0; i < 10; i++)
            Console.Write(randomTal1.Next(10,20)+" ");
        Console.WriteLine("\n\nNextDouble() som ger decimaltal mellan 0 och 1, 0<=x<1");
        for (i = 0; i < 10; i++)
            Console.WriteLine(randomTal1.NextDouble());
        Console.ReadKey();
    }
}
}

 

Källor

csharpskolan

MSDN Microsoft Visual C#

Skarp programmering, Jan Skansholm, Studentlitteratur 2011