0

I'm a newbie at c# at I was wondering why what I'm trying to do doesn't work.

 private int equation;
 public int Equation { get => equation; set => equation = value; }

    public void GainCaloriesMale(User user)
    {
        Equation = ((10 * user.Weight) + (6.25 * user.Height) - (5 * user.Age) + 5) + 250 + add;
        Console.WriteLine("\nBased on the Mifflin – St Jeor Formula You need to eat {0} Kalories a day To Gain Weight ", equation);
    }

Error CS0266 Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?)

Everything after equation is being underlined in red.

Thx for your time.

  • What is the error you're getting? Where is `equation` (not `Equation`, C# is case-sensitive) declared or defined? – Dai Jun 29 '18 at 04:27
  • 1
    It has nothing to do with properties... its just about assigning a double value to a variable/property of type int... You would get basically the same result when you assign to the field `equation` inside your method `GainCaloriesMale` – grek40 Jun 29 '18 at 05:13
  • Some ways out of your problem: https://stackoverflow.com/questions/4181942/convert-double-to-int and https://stackoverflow.com/questions/10754251/converting-a-double-to-an-int-in-c-sharp – grek40 Jun 29 '18 at 05:15

1 Answers1

2

You are multiplying ints with 6.25, which is a double literal, which converts the type of the right hand side expression to a double.

Either you gotta cast it explicitly as below. This will remove the decimal part of the expression result.

Equation =(int) ((10 * user.Weight) + (6.25 * user.Height) - (5 * user.Age) + 5) + 250 + add;

Or You can choose to change the type of variable equation to double too.

Ammar Ameerdeen
  • 950
  • 3
  • 11
  • 29