Math.Round - 不回答

时间:2015-05-06 00:08:51

标签: c# math methods

我想制作一个计算周长的程序。但是,更倾向于将圆形答案(小数点后两位)作为小数点后七位的姿势。但是当我使用Math.Round方法时,它似乎并不圆。我究竟做错了什么?

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

2 个答案:

答案 0 :(得分:2)

Math.Round不会修改提供的参数 - 它会返回一个新值。因此,您必须将其分配回变量才能使其正常工作:

ans = Math.Round(ans, 2);

答案 1 :(得分:1)

您必须使用Math.Round的返回值,它不会通过引用获取变量。

//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