0

I would like to make a program that calculates circumference. Though, would much rather have a rounded answer (two decimal places) as a pose to seven decimal places. But when I use the Math.Round method, it doesn't seem to round. What am I doing wrong?

Console.Write("Circumference Calculator! Enter the radius of the circle: ");
int inputRadius = Convert.ToInt32(Console.ReadLine());
double ans = Math.Sqrt(inputRadius) * Math.PI;
Math.Round(ans, 2);
Console.WriteLine("Your answer is: " + ans + " squared.");
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
MrBixbite
  • 39
  • 1
  • 1
  • 10
  • By *not* assigning the result of rounding, you're effectively calculating the rounding and **throwing the result away** without using it. As a general rule, variables only change when you assign them something (with `=`) but passing them around keep them the same. – Alejandro May 06 '15 at 00:14
  • Please don't spend half of the post in "thank you notes" and try to provide smallest possible sample... I tried to remove some code not strictly related to your question - feel free to roll back if you think I removed important details... – Alexei Levenkov May 06 '15 at 00:17
  • Note that what you probably trying to achieve is [Formatting a float to 2 decimal places](http://stackoverflow.com/questions/6356351/formatting-a-float-to-2-decimal-places) which usually done by using appropriate string format. – Alexei Levenkov May 06 '15 at 00:20

2 Answers2

2

Math.Round does not modify provided argument - it returns a new value. So you have to assigned it back to a variable to make it work:

ans = Math.Round(ans, 2);
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
1

You have to use the return value of Math.Round, it doesn't take the variable by reference.

//Greet user & give instructions
#region
Console.WriteLine("Circumference Calculator");
Console.WriteLine("");
Console.Write("Welcome to the Circumference Calculator! Please enter the radius of the circle: ");
#endregion

//Get input from user and calculate answer
#region
Console.ForegroundColor = oldColour;
int inputRadius = Convert.ToInt32(Console.ReadLine());
double ans = Math.Sqrt(inputRadius) * Math.PI;
Console.ForegroundColor = ConsoleColor.DarkYellow;
double roundedAnswer = Math.Round(ans, 2);
Console.WriteLine("Your answer is: " + roundedAnswer + " squared.");
#endregion
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445