Loading...

Във форума е въведено ограничение, което позволява на потребителите единствено да разглеждат публикуваните въпроси.

TodorovH avatar TodorovH 216 Точки

Ето и моето решение на задачата, като искам да изразя специални благодарности на двете дами по-горе, които ми дадоха много добри насоки, както и всички други в темата! Всеки допринесе за кода, малко или повече! Научих много за различните цикли, преобразувания и така нататък от задачата! Моля за проверка и предложения за оптимизации! Предварително благодаря!

Кода пресмята на колко сте години и на колко ще бъдете след 10 години, като взема за база рожденната дата! Преобразува стринговете в числа, взема си деня и месеца, и изчислява  точно възрастта ви!

http://pastebin.com/Gd9DyRbj
1
nikolay.dimov83 avatar nikolay.dimov83 143 Точки
Изпипал си я, браво!
0
mzografski avatar mzografski 189 Точки

Браво и на теб, 

DateTime обекта има един член, който се казва DayOfYear и връща поредния номер на деня на датата в годината. 

Така математическото решението на задачата може да мине с два реда:

 ageNow = nowDate.Year - dofb.Year - (dofb.DayOfYear < nowDate.DayOfYear ? 0 : 1);
 ageThen = ageNow + 10;


2
TodorovH avatar TodorovH 216 Точки
Благодаря!!! Постоянно научавам по нещо ново от форума! Оптимизиране до дупка за по-чист и подреден код! :)
0
aslv1 avatar aslv1 304 Точки
Actually we cannot unambiguously convert
time period (the difference between two days) to period, including month and years.
An example: 3 years may equals 1095 days or 1096 days.
Of course, if we have two fixed dates, the period is exactly defined,
but there is not such an integrated tool in .NET, so we can either calculate periods
in dates (but in that case we cannot just add "10 years"), or to use approximate values.

P. S. Here there is a solution, but it gets too complex for "C# Basics"!
0
nikolay.dimov83 avatar nikolay.dimov83 143 Точки

Ето и читаво решение от мен - проверки за читав формат на въведена дата + проверка за въведена дата на раждане в бъдещето:

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


namespace _15a.AgeAfter10years_SOLUTION_WITH_DATES
{
    class Program
    {
        static void Main(string[] args)
        {
          string StrDateBirth;
          Console.WriteLine("Please enter the date you were born"); 
          StrDateBirth = Console.ReadLine();


DateTime DateBirth;




if (DateTime.TryParse(StrDateBirth, out DateBirth))
{
    //Checks for correct date time input
    Console.WriteLine("  Converted '{0}' to {1} ({2}).", StrDateBirth,
                        DateBirth, DateBirth.Kind);
    DateBirth = DateTime.Parse(StrDateBirth);
    Console.WriteLine(DateBirth);
    int YearBirth = DateBirth.Year;
    DateTime DateNow = DateTime.Today;
    int YearNow = DateNow.Year;
    int Age = YearNow - YearBirth;
    //checks whether user has entered date in the future as his birthday
    if (Age > 0)
    {
        Console.WriteLine("Your age in ten years is {0}", (Age + 10));
    }
    else
        Console.WriteLine("You have entered Birth Year that is after current year");
}


else
    Console.WriteLine("  This is not correct Date/Time Format '{0}', Please enter correct Date/Time format", StrDateBirth);
         


        }
    }
}

0
TodorovH avatar TodorovH 216 Точки
Кода изпечатва неща, които са си само за вътрешна употреба, ако може така да се каже! И не смята вярно, защото не отчита дали е минала рожденната дата! Виж моя код и кажи какво мислиш, моля!?
0
glava avatar glava 0 Точки
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace _15.Age
{
    class age
    {
        static void Main()
        {
           
            int day;
            int month;
            int year;
            int age;
            Console.WriteLine("Day");
            day = int.Parse(Console.ReadLine());
           
            Console.WriteLine("Month?");
            month = int.Parse(Console.ReadLine());
            
            Console.WriteLine("Year?");
            year = int.Parse(Console.ReadLine());
            DateTime today = DateTime.Today;
            DateTime bday = new DateTime(year, month, day);




            age = today.Year - bday.Year;
            if (today.Month < bday.Month || (today.Month < bday.Month && today.Day < bday.Day) || (today.Month == bday.Month && today.Day < bday.Day))
            {
                age--;


            }
           Console.WriteLine("You are " + age + " years old and after 10 years you will be " + (age+10) + " years old");


        }


    }
}
0
ybaltova avatar ybaltova 14 Точки

Едно възможно решение и от мен:

Console.WriteLine("Enter your birthdate in the format yyyy/mm/dd");
            DateTime dateOfBirth = DateTime.Parse(Console.ReadLine());
            DateTime dateToday = DateTime.Now;
            int age = dateToday.Year - dateOfBirth.Year;
            if (dateToday.Month < dateOfBirth.Month || (dateToday.Month == dateOfBirth.Month && dateToday.Day < dateOfBirth.Day))
            {
                age--;
            }
            Console.WriteLine("You are " + age + " years old.");
            Console.WriteLine("In 10 years you will be " + (age + 10) + " years old.");

2
IvMironov avatar IvMironov 35 Точки

Здравейте,

Ето и моето решение:

using System;

class TenYearsOld
{
static void Main()
{
DateTime birthDate;
DateTime datenow = DateTime.Now;
Console.Write("Please enter your date of birth (yyyy/mm/dd):");
birthDate = DateTime.Parse(Console.ReadLine());
int currAge = datenow.Year - birthDate.Year;
if (datenow.Month < birthDate.Month || (datenow.Month == birthDate.Month && datenow.Day < birthDate.Day)) currAge--;
Console.WriteLine("Your current age is: {0} years", currAge);
int tenYOld = currAge + 10;
Console.WriteLine("After ten years you will be on: {0} years", tenYOld);
}
}

Поздрави

0
achkata avatar achkata 17 Точки

Ето моето решение (използвани са и неща, които все още не са преподадени, но ме дояде да оставя незавършена задачата).

using System;

class PrintAgeChange
{

       static int den;
       static int mesec;
       static int godina;
       static Boolean correctDate = false;
       static DateTime birthDate;
       static void Main()
       {
            do
            {
                  readDate();
            } while (!correctDate);

            DateTime currentDay = DateTime.Today;
            Console.WriteLine("В момента сте на " + GetAge(birthDate, currentDay) + " г.");
            Console.WriteLine("След 10 години ще бъдете на " + GetAge(birthDate, currentDay.AddYears(10)) + " г.");
      }//end of Main()

      public static void readDate()
      {
            try
            {
                   Console.WriteLine();
                   Console.Write("Въведете ден на раждане (число): ");
                   den = Convert.ToInt32(Console.ReadLine());
                   Console.Write("Въведете месец на раждане (число): ");
                   mesec = Convert.ToInt32(Console.ReadLine());
                   Console.Write("Въведете година на раждане: ");
                   godina = Convert.ToInt32(Console.ReadLine());
                   birthDate = new DateTime(godina, mesec, den);
                   correctDate = true;
            }
            catch (Exception e)
            {
                  correctDate = false;
            }

       }//end of readDate()


      public static int GetAge(DateTime birthDate, DateTime now)
      {
            int age = now.Year - birthDate.Year;
            if (now.Month < birthDate.Month || (now.Month == birthDate.Month && now.Day < birthDate.Day)) age--;
            return age;
      }//end of GetAge
}// end of class

 

0
Можем ли да използваме бисквитки?
Ние използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Можете да се съгласите с всички или част от тях.
Назад
Функционални
Използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Използваме „сесийни“ бисквитки, за да Ви идентифицираме временно. Те се пазят само по време на активната употреба на услугите ни. След излизане от приложението, затваряне на браузъра или мобилното устройство, данните се трият. Използваме бисквитки, за да предоставим опцията „Запомни Ме“, която Ви позволява да използвате нашите услуги без да предоставяте потребителско име и парола. Допълнително е възможно да използваме бисквитки за да съхраняваме различни малки настройки, като избор на езика, позиции на менюта и персонализирано съдържание. Използваме бисквитки и за измерване на маркетинговите ни усилия.
Рекламни
Използваме бисквитки, за да измерваме маркетинг ефективността ни, броене на посещения, както и за проследяването дали дадено електронно писмо е било отворено.