0

I am having trouble rounding a number in C#. Here is my code:

public static double GetHighTargetHR (string birthdate, string examDate)
{
  double HighTargetHR = 0;
  double age;
  double constant = 220;

  age = CalculateAge(birthdate, examDate);

  if (age > 0)
  {
    HighTargetHR = ((constant - age) * 0.8);
    Math.Round(HighTargetHR, 0, MidpointRounding.AwayFromZero);
  }

  return HighTargetHR;
}

This patient's age is 26. So 220-26 = 194 * 0.8 = 155.20

I want the code to return 155. No matter what I change on the Math.Round function, it returns 155.20. How can I make it return an even number?

elderboy02
  • 27
  • 5
  • 8
    `Math.Round()` returns the rounded value. You're ignoring the return value. – CodeCaster Nov 27 '17 at 15:17
  • 1
    As Pac0 and CodeCaster mentioned, you're not returning the result of your rounding call, you're just throwing it away. – Blair Scott Nov 27 '17 at 15:18
  • 3
    `Int`s are value types. They are not passed by reference (like reference types) into methods so cannot be manipulated. Hence the method returns a value. See [What is the difference between a reference type and value type in c#?](https://stackoverflow.com/questions/5057267/what-is-the-difference-between-a-reference-type-and-value-type-in-c) – Liam Nov 27 '17 at 15:19
  • @Liam Reference types or value types are not passed by reference unless `ref` our `out` is specified. – Magnus Nov 27 '17 at 15:22

3 Answers3

2

You have to affect the result of Math.Round to the variable. Otherwise, it is simply discarded.

 HighTargetHR = Math.Round(HighTargetHR, ...);
Pac0
  • 21,465
  • 8
  • 65
  • 74
0

You need to assign the result of the function you are using (Math.Round):

HighTargetHR = Math.Round((constant - age) * 0.8, 0, MidpointRounding.AwayFromZero);

A function returns a value; so, when you use some function, you have to assign its returned value to a variable.

Dalton Cézane
  • 3,672
  • 2
  • 35
  • 60
-1

You are missing to use the return type of round function.

HighTargetHR = Math.Round(HighTargetHR, 0, MidpointRounding.AwayFromZero);
Liam
  • 27,717
  • 28
  • 128
  • 190
Manish Dubey
  • 706
  • 4
  • 17