Im计算数组中正整数,负整数和零的比率。我想将比率四舍五入到小数点后六位。
using System;
namespace PlussMinussRatio
{
class MainClass
{
public static void Main(string[] args)
{
int[] array = new int[] { -4, 3, -9, 0, 4, 1 };
Solution(array);
}
public static void Solution(int[] arr)
{
float positive = 0, negative = 0, zero = 0;
float positiveRatio = 0, negativeRatio = 0, zeroRatio = 0;
float arrLength = arr.Length;
for(int i = 0;i < arrLength; i++)
{
if(arr[i] < 0)
{
negative++;
}
else if(arr[i] > 0)
{
positive++;
}
else
{
zero++;
}
}
positiveRatio = positive / arrLength;
negativeRatio = negative / arrLength;
zeroRatio = zero / arrLength;
Math.Round(positiveRatio, 6);
Math.Round(negativeRatio, 6);
Math.Round(zeroRatio, 6);
//Console.WriteLine(positive + " " + negative + " " + zero);
Console.WriteLine(positiveRatio + "\n" + negativeRatio + "\n" + zeroRatio);
}
}
}
这就是我得到的:
0.5 0.333333 0.166667 我希望0.5为0.500000。该怎么办?
答案 0 :(得分:0)
您将忽略Math.Round()的返回值。它返回舍入的值。
但是您不需要Math.Round(),需要一个格式字符串:
b