C# Ошибка во время инициализации элементов объекта

348
04 апреля 2018, 08:01

Здравствуйте. В программе я создаю несколько классов с наследованием. Во время выполнения метода ExperienceInPercent получаю в результате 0, а значит, где-то я неправильно инициализирую элементы класса (по всей видимости, Age и YearExperience). Помогите, пожалуйста, обнаружить ошибку.

using System;
namespace Laboratory_work
{
    class Program
    {   
    public delegate int Delegate ();
    public interface Method1
    {
        string InformationOutput (Person obj);
    }
    public interface Method2
    {
        int WorkOffer();
        int Invitation();
    }
    public interface Method3
    {
        void ExperienceInPercent(int a, int b);
        void EquippedOrNot(int c, int d);
    }
    public abstract class Person: Method1
    {
        public string Name{get; set;}
        public string Surname{get; set;}
        public int Age{get; set;}
        public virtual string InformationOutput(Person obj)
        {
            string info="Some personal information \n_________________________\n\n"+
                "Full name — "+Name+" "+Surname+
                "\nAge — "+Age+" years\n";
            return info;
        }   
    }
    public class WhiteCollarWorker: Person, Method1
    {
        public string Occupation{get; set;}
        public bool ComputerAvailable{get; set;}
        public int ComputerNumber{get; set;}
        public bool TeamExistence{get; set;}
        public int TeamParticipants{get; set;}
        public override string InformationOutput(Person obj)
        {
            return base.InformationOutput(obj)+"Occupation — "+Occupation+"\n"+
                "Computer — "+ComputerAvailable+"\n";
        }
    }
    public class Engineer: WhiteCollarWorker, Method1, Method2, Method3
    {
        public int YearExperience{get; set;}
        public bool BachelorDegree{get; set;}
        public bool MasterDegree{get; set;}
        public override string InformationOutput(Person obj)
        {
            return base.InformationOutput(obj)+"Experience — "+YearExperience+" year(s)\n"+
                "Bachelor Degree — "+BachelorDegree+"\n"+
                "Master Degree — "+MasterDegree+"\n";
        }
        public int WorkOffer()
        {
            if (Age>=21 && YearExperience>=1 && BachelorDegree==true)
            {return 1;}
            else 
            {return 0;}
        }
        public int Invitation()
        {
            if(WorkOffer()==1)
            {
                Console.WriteLine("\nDear "+Name+" "+Surname+", soon you will receive\n"+
                               "an email with date and time of your interview\n"+
                               "at out company.Thank you for your CV.");
                return 1;                  
            }
            else
            {
                Console.WriteLine("\nDear "+Name+" "+Surname+", unfortunately, you are\n"+
                               "not suitable for this position. Than you for your CV.\n");
                return 0;  
            }
        }
        public void ExperienceInPercent(int YearExperience, int Age) 
        {
            try
            {
                double result=(YearExperience/Age)*100;
                Console.WriteLine("The part of life spent for working: "+result+" %");
            }
            catch(DivideByZeroException example)
            {
                Console.WriteLine("Error "+example+" captured in ExperienceInPercent method");
                Console.Write("Input the right value of Age: ");
                Age=int.Parse(Console.ReadLine());
                double result=(YearExperience/Age)*100;
                Console.WriteLine("The part of life spent for working: "+result+" %");
            }
        }
        public void EquippedOrNot(int ComputerNumber, int TeamParticipants)
        {
            try
            {
                double result=(ComputerNumber/TeamParticipants)*100;
                Console.WriteLine("How much the team is equipped: "+result+" %");
            }
            catch(DivideByZeroException example)
            {
                Console.WriteLine("Error "+example+" captured in EquippedOrNot method");
                Console.Write("Input the right number of the team perticipants: ");
                TeamParticipants=int.Parse(Console.ReadLine());
                double result=(ComputerNumber/TeamParticipants)*100;
                Console.WriteLine("How much the team is equipped: "+result+" %");
            }
        }
    }
    public static void Main()
    {
        const int N=10;
        int Count=0;
        var persons1=new Engineer[N];   
        for (int i=0; i<10; i++)
        {
            persons1[i] = new Engineer();
            Delegate DELnum1=persons1[i].WorkOffer;
            Delegate DELnum2=persons1[i].Invitation;
            Delegate DDEL=DELnum1+DELnum2;
            Console.WriteLine("\n\nENGINEERS\n________\n");
            Console.WriteLine("Input information of a person");
            Console.Write("Name: ");
            persons1[i].Name=Console.ReadLine();
            Console.Write("Surname: ");
            persons1[i].Surname=Console.ReadLine();
            Console.Write("Age: ");
            persons1[i].Age=int.Parse(Console.ReadLine());
            Console.Write("Occupation: ");
         persons1[i].Occupation=Console.ReadLine();
            Console.Write("Computer (true or false): ");
            persons1[i].ComputerAvailable=bool.Parse(Console.ReadLine());
            if (persons1[i].ComputerAvailable==true)
            {
                Console.Write("Number of computers: ");
                persons1[i].ComputerNumber=int.Parse(Console.ReadLine());
            }
            Console.Write("Team (true or false): ");
            persons1[i].TeamExistence=bool.Parse(Console.ReadLine());
            if (persons1[i].TeamExistence==true)
            {
                Console.Write("Number of participants of the team: ");
                persons1[i].TeamParticipants=int.Parse(Console.ReadLine());
            }
            Console.Write("Experience (in years): ");
            persons1[i].YearExperience=int.Parse(Console.ReadLine());
            Console.Write("Bachelor Degree (true or false): ");
            persons1[i].BachelorDegree=bool.Parse(Console.ReadLine());
            Console.Write("Master Degree (true or false): ");
            persons1[i].MasterDegree=bool.Parse(Console.ReadLine());
            DDEL(); 
            Count++;
            Console.WriteLine("\nDo you want to continue? (Print 'OK' or 'NO'.)");
            string answer;
            answer=Console.ReadLine();
            if (answer=="OK"||answer=="ok") continue;
            else break;
        }
        for(int i=0; i<Count;i++)
        {
            Delegate DELnum1=persons1[i].WorkOffer;
            Console.WriteLine("\n\n#"+(i+1));
            Console.WriteLine(persons1[i].InformationOutput(persons1[i]));
            if (DELnum1()==1) Console.WriteLine("Accepted for work.");
            else Console.WriteLine("Not accepted for work.");
            persons1[i].ExperienceInPercent(persons1[i].YearExperience, persons1[i].Age);
            if (persons1[i].ComputerNumber!=0)
                persons1[i].EquippedOrNot(persons1[i].ComputerNumber, persons1[i].TeamParticipants);
        }
        Console.WriteLine("\nPress any key to continue . . .");
        Console.ReadKey(true);
    }
    }
}
Answer 1

У вас деление целочисленных переменных. Данные теряются.

double result = (YearExperience / Age) * 100;

YearExperience / Age - обе целочисленные - результат тоже целое будет, причем YearExperience нацело на Age не делится - следовательно берется только целая часть - 0. А ноль умноженное хоть на миллион будет ноль.

Достаточно написать что-то типа того:

double result = ((float)YearExperience / Age) * 100;

Тогда расчеты принудительно будут проводиться в числах с плавающей запятой и все будет хорошо, разве что значения будут получиться типа 23,8464849463% - придется округлять.

Так что инициализация более менее работает, я уж промолчу про то как она работает - вопрос ведь был не в этом. Почему самостоятельно не прошлись пошагово дебагером, а? Все же элементарно.

P.S. C-style код - нужно отвыкать, здесь вам не там)

READ ALSO
CSS Grid в 2018?

CSS Grid в 2018?

Недавно разобрался в CSS Grid, и понял что это лучшее для меня решение в плане позиционирования элементов

247
Как сделать такой эффект как на скриншоте с эффектом смещения?

Как сделать такой эффект как на скриншоте с эффектом смещения?

Хотелось бы реализовать такой эффект как на скрине :

317
Как разместить блок под блоком с абсолютным позиционированием

Как разместить блок под блоком с абсолютным позиционированием

Есть блок c position:absolute, нужно под ним разместить блок так, чтобы он не наплывал на предыдущий (не всхлопывался)При этом он должен быть в рамках...

301
&lt;b&gt;Notice&lt;/b&gt;: Undefined variable: _Get in

<b>Notice</b>: Undefined variable: _Get in

Добрый деньПытаюсь настроить проброс меток через преленд

288