כתבו קטע תכנית אשר מקבל 6 מספרים שלמים. קטע תכנית זה ידפיס את זוג הנקודות שאורכו הוא הגדול ביותר מבין שלושת צלעות המשולש.

שימו לב שקטע התכנית נכתב לא באופן הכי טוב (בכוונה), מפני שהוא מהווה שאלה התחלתית מאוד בתכנות ומלמד על שימוש בספריית Math.

אתגר:

אם אתם יודעים ליצור פונקציות, שפרו את קטע התכנית כך שיעבוד עם יותר פונקציות ופחות קוד חזרתי.כך גם תבינו את משמעות ויתרונות השימוש של פונקציות וכתיבת קוד נקי יותר.

פתרון מלא בשפת Java:

import java.util.*;

public class Main

{

   

    public static double distance(int x1,int y1, int x2, int y2)

    {

       

        double diff1 =  (x1-x2);

        double diff2 =  (y1-y2);

       

     //√(diff1^2+diff2^2)

        return Math.sqrt(diff1*diff1+diff2*diff2);

    }

   

        public static void main(String[] args) {

           

            Scanner scan = new Scanner(System.in);

               

                System.out.println("Please enter coordinates (int numbers) for 3 points");

                

                

                //A

                int x1 = scan.nextInt();

                int y1 = scan.nextInt();

                

                //B

                int x2 = scan.nextInt();

                int y2 = scan.nextInt();

                

                //C

                int x3 = scan.nextInt();

                int y3 = scan.nextInt();

                double dAB = distance(x1,y1,x2,y2);

                double dAC = distance(x1,y1,x3,y3);

                double dBC = distance(x2,y2,x3,y3);

                

                if(dAB == Math.max(Math.max(dAB,dAC),dBC))

                System.out.println("The points of the triangle whose sides are the longest: "+"("+x1+","+y1+"), ("+x2+","+y2+").");

                

                else if(dAC == Math.max(Math.max(dAB,dAC),dBC))

                System.out.println("The points of the triangle whose sides are the longest: "+"("+x1+","+y1+"), ("+x3+","+y3+").");

                

                else

                System.out.println("The points of the triangle whose sides are the longest: "+"("+x2+","+y2+"), ("+x3+","+y3+").");

                

        }

}