【发布时间】:2020-01-19 22:46:36
【问题描述】:
我只需要为我的作业完成这个程序,并且我已经完成了我希望它执行的任务,但我一生无法弄清楚如何让我的输出显示数字值到秒十进制。 (例如:35.50)
我的程序旨在取值的平均值,并以小数形式给出数值平均值。它确实这样做了,但是十进制字符串比小数点后 2 位要长。我希望就如何清理这个问题得到一些建议,并请给出所有答案并附上解释。太感谢了! (我使用的程序是visual studios 2017,我在C#的控制台应用程序中创建这个代码)
static void Main(string[] args)
{
decimal counter = 1;
decimal sum = 0;
decimal totalLoops = 3;
while (counter <= totalLoops)
{
Console.WriteLine("Please enter test score here:");
string scoreInput = Console.ReadLine();
decimal score;
decimal.TryParse(scoreInput, out score);
sum += score;
counter++;
}
Console.WriteLine("Your average is {0}", decimal.Round(sum, 2) / decimal.Round(totalLoops, 2));
Console.ReadKey();
}
}
【问题讨论】:
-
"Your average is {0:N2}" -
访问stackoverflow.com/questions/15288134/… *value.ToString("0.00");
-
我还强烈建议不要在进行数学计算时进行舍入直到最后一次可能的计算。换句话说,不要将两个数字四舍五入然后除以它们。相反,在最后进行除法和舍入 一次 以获得输出(或使用我建议的技术来避免显式舍入的需要)。
标签: c# decimal console-application rounding