Регистрация не е нужна, освен при създаване на тема в "Задача на седмицата".

Задача за създаване на конзолна програма

Задача за създаване на конзолна програма

Мнениеот Гост » 12 Апр 2022, 12:22

Здравейте, може ли помощ за една от тези задачи?

1.Съставете конзолно приложение, което по зададена дата да извежда на следващата дата. Датата се въвежда в три целочислени променливи.

2.Създайте конзолна програма за определяне на третата страна на правоъгълен триъгълник. Възможни са два случая третата страна да е катет или хипотенуза. Програмата да изисква въвеждане на информация за търсената страна, ако е хипотенуза се въвежда ‘h’ , ако е катет ‘k‘
Гост
 

Re: Задача за създаване на конзолна програма

Мнениеот ammornil » 14 Апр 2022, 22:00

За датите в C# предлагам нещо такова.

Клас Основен
Код: Избери целия код
using System;

namespace Dati
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //брояч на повторения
            int rept = 0;
            //започва цикъл от десет изпълнения на кода (не брои случаите с грешно въведени данни)
            while (rept < 10)
            {
                Datnik dt = new Datnik();
                dt.GetDateFromUser();
                if (dt.IsDisplayable)
                {
                    Console.WriteLine("The date after {0} is {1}", dt.DateString, dt.Utre());
                }
                Console.ReadKey(true);
                rept++;
            }           
        }
    }
}


Клас Манипулации за дати
Код: Избери целия код
using System;
using System.Collections.Generic;
using System.Text;

namespace Dati
{
    internal class Datnik
    {
        public static readonly string[] Meseci = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
        public int Den { get; set; }
        public int Mesec { get; set; }
        public int Godina { get; set; }
        public string DateString { get; set; }
        public bool IsDisplayable { get; set; }

        public Datnik()
        {
            this.IsDisplayable = true;
        }

        public Datnik(int d, int m, int g)
        {
            if (m == 2 && d > 29)
            {
                if (g % 4 == 0)
                {
                    d = 29;
                }
                else
                {
                    d = 28;
                }
            }
            int mDays = SetMaxDays(m,g);
            this.Den = (d<=mDays) ? d : mDays;
            this.Mesec = (m > 0 && m < 13) ? m : 1;
            this.Godina = g;
            this.DateString = String.Format("{0 :00}/{1 :00}/{2 :00}",d,m,g);
            this.IsDisplayable = true;
        }

        public void GetDateFromUser()
        {
            byte nDay;
            byte nMes;
            int nGod;
            Console.Write("Please enter the day of the date: ");
            try
            {
                nDay = byte.Parse(Console.ReadLine());
            }
            catch
            {
                Console.WriteLine("Invalid Input: The data you have entered was not numeric or the number was out of range.");
                this.IsDisplayable = false;
                return;
            }
            Console.Write("Please enter the month of the date: ");
            try
            {
                nMes = byte.Parse(Console.ReadLine());
            }
            catch
            {
                Console.WriteLine("Invalid Input: The data you have entered was not numeric or the number was out of range.");
                this.IsDisplayable = false;
                return;
            }
            Console.Write("Please enter the year of the date: ");
            try
            {
                nGod = int.Parse(Console.ReadLine());
            }
            catch
            {
                Console.WriteLine("Invalid Input: The data you have entered was not numeric or the number was out of range.");
                this.IsDisplayable = false;
                return;
            }
            if (nGod < 0 || nMes < 0 || nDay < 0)
            {
                Console.WriteLine("Invalid Input: The day, month and year must be positive whole numbers.");
                this.IsDisplayable = false;
                return;
            }
            if (nMes<1 || nMes > 12)
            {
                Console.WriteLine("Invalid Input: The month must be a whole number between 1 and 12.");
                this.IsDisplayable = false;
                return;
            }
            int mDays = SetMaxDays(nMes,nGod);
            if (nDay > mDays)
            {
                Console.WriteLine("Invalid Input: The month of {0} in year {1} has only {2} days.", Meseci[nMes-1],nGod,mDays);
                this.IsDisplayable = false;
                return;
            }
            this.Den = nDay;
            this.Mesec = nMes;
            this.Godina = (nGod<100) ? nGod+2000 : nGod;
            this.DateString = String.Format("{0 :00}/{1 :00}/{2 :00}", nDay, nMes, nGod);
            this.IsDisplayable = true;
            return;
        }

        public string Utre()
        {
            int mDays = SetMaxDays(this.Mesec, this.Godina);
            int nDay;
            int nMes;
            if (this.Den + 1 > mDays)
            {
                nDay = 1;
                nMes = this.Mesec + 1;
            }
            else
            {
                nDay = this.Den + 1;
                nMes = this.Mesec;
            }
            if (nMes < 13)
            {
                return String.Format("{0 :00}/{1 :00}/{2 :00}", nDay, nMes, this.Godina);
            }
            else
            {
                return String.Format("{0 :00}/{1 :00}/{2 :00}", nDay, 1, this.Godina + 1);
            }
        }

        public int SetMaxDays(int ms, int gd)
        {
            int maxDays;
            switch (ms)
            {
                case 1:
                case 3:
                case 5:
                case 7:
                case 8:
                case 10:
                case 12:
                    maxDays = 31;
                    break;
                case 2:
                    if (gd % 4 == 0)
                    {
                        maxDays = 29;
                    }
                    else
                    {
                        maxDays = 28;
                    }
                    break;
                case 4:
                case 6:
                case 9:
                case 11:
                    maxDays = 30;
                    break;
                default:
                    maxDays = 28;
                    break;
            }           
            return maxDays;
        }
       
    }
}

[tex]\color{lightseagreen}\text{''Който никога не е правил грешка, никога не е опитвал нещо ново.''} \\
\hspace{21em}\text{(Алберт Айнщайн)}[/tex]
Аватар
ammornil
Математик
 
Мнения: 3759
Регистриран на: 25 Май 2010, 19:28
Местоположение: Великобритания
Рейтинг: 1774

Re: Задача за създаване на конзолна програма

Мнениеот ammornil » 15 Апр 2022, 23:34

За страните на правоъгълния триъгълник в C# предлагам нещо такова.

Главен метод (основен клас)
Код: Избери целия код
using System;

namespace PravoygTriygylnik
{
    internal class Program
    {
        static void Main(string[] args)
        {
            int turn = 0;
            while (turn < 5)
            {
                Console.WriteLine("\n\n Repetition {0} of 5", turn + 1);
                PravoygTriyg pt = new PravoygTriyg();
                pt.ProcessTriangleData();
                turn++;
            }
            Console.WriteLine("Thank you! Good bye!");
            Console.ReadKey(true);
        }
    }
}


Работен метод (клас за основния обект)
Код: Избери целия код
using System;
using System.Collections.Generic;
using System.Text;

namespace PravoygTriygylnik
{
    internal class PravoygTriyg
    {
        public double SideA { get; set; }
        public double SideB { get; set; }
        public char MissingSide { get; set; }

        public PravoygTriyg()
        {
           
        }

        public PravoygTriyg(double a, double b, char ch)
        {
            this.SideA = a;
            this.SideB = b;
            this.MissingSide = ch;
        }

        public void ProcessTriangleData()
        {
            double a, b;
            char ch;
            Console.Write("Enter length of one side of a rectangular triangle:\t\t");
            try
            {
                a = double.Parse(Console.ReadLine());
            }
            catch
            {
                this.ErrorMsg1();
                return;
            }
            Console.Write("Enter length of another side of a rectangular triangle:\t\t");
            try
            {
                b = double.Parse(Console.ReadLine());
            }
            catch
            {
                this.ErrorMsg1();
                return;
            }
            if (a < 0 || b < 0)
            {
                this.ErrorMsg1();
                return;
            }
            Console.Write("Enter which side's size is missing (type 'h' for hypothenuse or 'k' for cathetus):\t");
            ch = char.Parse(Console.ReadLine());
            if (ch != 'h' && ch != 'k')
            {
                this.ErrorMsg2();
                return;
            }
            this.SideA = a;
            this.SideB = b;
            this.MissingSide = ch;
            this.CalcMissingSide();
        }

        public void CalcMissingSide()
        {
            if (this.SideA == this.SideB && this.MissingSide != 'h')
            {
                Console.WriteLine("Rectangular triangle cannot have cathetus equal to the hypotenuse.");
                return;
            }
            if (this.MissingSide == 'h')
            {
                Console.WriteLine("Rectangular triangle with catheti {0, 8 : 0.0000} and {1, 8 : 0.0000} has a hipothenuse of {2, 8 : 0.0000}",
                    this.SideA, this.SideB, Math.Sqrt(Math.Pow(this.SideA,2)+Math.Pow(this.SideB,2)));
            }
            else
            {
                Console.WriteLine("Rectangular triangle with hypothenuse {0, 8 : 0.0000} and cathetus {1, 8 : 0.0000} has other cathetus of {2, 8 : 0.0000}",
                    (this.SideA>this.SideB) ? this.SideA : this.SideB,
                    (this.SideA > this.SideB) ? this.SideB : this.SideA,
                    Math.Sqrt(Math.Abs(Math.Pow(this.SideA, 2) - Math.Pow(this.SideB, 2))));
            }
        }

        public void ErrorMsg1()
        {
            Console.WriteLine("The data entered was in wrong format. Please enter a positive numbers only. If your input is of decimal type use . as decimal sign");
        }

        public void ErrorMsg2()
        {
            Console.WriteLine("The data entered was in wrong format. The axceptable characters are 'h' for hypothenuse or 'k' for cathetus.");
        }
    }
}

[tex]\color{lightseagreen}\text{''Който никога не е правил грешка, никога не е опитвал нещо ново.''} \\
\hspace{21em}\text{(Алберт Айнщайн)}[/tex]
Аватар
ammornil
Математик
 
Мнения: 3759
Регистриран на: 25 Май 2010, 19:28
Местоположение: Великобритания
Рейтинг: 1774


Назад към C#, Java



Кой е на линия

Регистрирани потребители: Google [Bot]

Форум за математика(архив)
cron