C# Calculator Class

前端 未结 4 913
太阳男子
太阳男子 2021-01-17 00:36

I was given this homework assignment, which I have been having a hard time with. The form was written and we had to write the class. Currently when I run the program my equa

4条回答
  •  灰色年华
    2021-01-17 01:23

    displayValue is both a class field and a method argument. Is that your intention? You need to make this.displayValue = ... when you assign to the field argument in order to make it clear what you are doing. Currently you are overwriting the local copy of the argument and the field value is always 0.

    Just delete the decimal displayValue; declaration (and from the Clear() function) and then store the displayValue outside of the class in the form.

    public class Calculator
    {
    
        //public Decimal displayValue;
        public Decimal currentValue;
    
        public void Add(Decimal displayValue)
        {
    
            currentValue+=displayValue;
    
        }
        ...
        public void Clear()
        {
            currentValue=0;
            //displayValue=0;
        }
    
        public decimal CurrentValue
        {
            get { return currentValue; }
    
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            Calculator calc=new Calculator();
            calc.Add(1000m);
            calc.Divide(25m);
            calc.Subtract(8m);
    
            Console.WriteLine(calc.CurrentValue);
            // (1000/25)-8 = 32
        }
    }
    

提交回复
热议问题