C#中for循环中的多个随机数

时间:2015-11-12 16:59:34

标签: c# random numbers

这里编程新手。我正在尝试为我的积分生成随机坐标 但我得到的数字相同,如(1,1),(2,2)(5,5)等

我将随机发生器置于循环之外,但这并没有帮助。

我的输出看起来像这样

点#0(4,4) 点#1(8,8) 点#2(9,9) 要点三(1,1) 点#4(0,0)

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

namespace dotsGrids
{
    class Program
    {
        static void Main(string[] args)
        {
            Grid grid = new Grid(9,5);            

            Console.WriteLine(grid.RenderGrid());

            Console.WriteLine("END.");
            Console.ReadKey();
        }
    }
    class Point
    {        
        public int x, y;
        public Point(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
    }
    class Grid
    {
        static Random r = new Random();
        int size;
        int tempx, tempy;
        Point[] p;

        public Grid(int size,int numOfPoints)
        {
            this.size = size;
            p = new Point[numOfPoints];
            for (int i = 0; i < numOfPoints; i++)
            {
                tempx = r.Next(10);
                tempy = r.Next(10);
                p[i] = new Point(tempx,tempy);
            }
        }
        public string RenderGrid()
        {
            string s = " ";
            string sum = "";
            bool flag = true;
            for(int i=1;i<= size; i++)
            {
                s += " " + i;
            }
            s += "\n";
            for (int y=1;y<= size; y++)
            {
                s += y;
                for (int x = 1;x<= size; x++)
                {                    
                    for (int j = 0; j < p.Length; j++)
                    {                        
                        if (p[j].x == x && p[j].y == y)
                        {                            
                            if(p[j].x + p[j].y+"" != sum)//Prevent additional * if same coordinates
                            {
                                s += " *";
                            }
                            sum += p[j].x + p[j].y;
                            flag = false;
                        }
                    }
                    if(flag) s += " -";
                    flag = true;
                }
                s += "\n";
            }
            s += "\n"; s += "\n"; s += "\n";
            for (int i = 0; i < p.Length; i++)
            {
                s += "Point#" + i + "(" + p[i].x + "," + p[i].x + ")";
                s += "\n";
        }
        return s;
    }
}

}

1 个答案:

答案 0 :(得分:3)

我认为您需要更改此行:

s += "Point#" + i + "(" + p[i].x + "," + p[i].x + ")";

到此:

s += "Point#" + i + "(" + p[i].x + "," + p[i].y + ")";

您正在两次打印x坐标,而不是x和y坐标。