MrBixbite
MrBixbite

Reputation: 39

Math.Round - Does not round answer

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.");

Upvotes: 0

Views: 442

Answers (2)

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

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);

Upvotes: 2

Daniel A. White
Daniel A. White

Reputation: 190925

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

Upvotes: 1

Related Questions