C#物件導向思想計算兩點之間距離

來源:互聯網
上載者:User

標籤:

題目為計算兩點之間距離。

面向過程的思維方式,兩點的橫座標之差,縱座標之差,平方求和,再開跟,得到兩點之間距離。

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Classes_2_point_distance{    class Program    {        static void Main(string[] args)        {            int x1 = -1;            int y1 = -1;            int x2 = int.Parse(Console.ReadLine());            int y2 = int.Parse(Console.ReadLine());            int xdiff = x2 - x1;            int ydiff = y2 - y1;            double distance = Math.Sqrt(xdiff * xdiff + ydiff * ydiff);            Console.WriteLine(distance);            Console.ReadKey();        }    }}

  物件導向的思路,題目中,兩點間直線距離,名詞包括點、直線、距離,首先我們構造一個點類。

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Classes_2_point_distance{    class Point    {        private int x;        private int y;        public Point()        {            x = -1;            y = -1;        }        public Point(int h, int z)        {            x = h;            y = z;        }        public double Distance(Point p)        {            int xdiff = x - p.x;            int ydiff = y - p.y;            return Math.Sqrt(xdiff * xdiff + ydiff * ydiff);                    }    }}

  

然後再Programe.cs中執行個體化p1,p2兩個點,計算距離

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Classes_2_point_distance{    class Program    {        static void Main(string[] args)        {            //int x1 = -1;            //int y1 = -1;            int x2 = int.Parse(Console.ReadLine());            int y2 = int.Parse(Console.ReadLine());            //int xdiff = x2 - x1;            //int ydiff = y2 - y1;            //double distance = Math.Sqrt(xdiff * xdiff + ydiff * ydiff);            //Console.WriteLine(distance);            //Console.ReadKey();            Point p1 = new Point();            Point p2 = new Point(x2, y2);            double distance = p1.Distance(p2);            Console.WriteLine(distance);            Console.ReadKey();        }    }}

  

C#物件導向思想計算兩點之間距離

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.