我希望在c#
中给出数字例如:
round(25)=50
round(250) = 500
round(725) = 1000
round(1200) = 1500
round(7125) = 7500
round(8550) = 9000
答案 0 :(得分:4)
您的大多数数据表明您想要舍入到最接近的500的倍数。这可以通过
完成int round(int input)
{
return (int)(500 * Math.Ceiling(input / 500.0));
}
但是,25到50的舍入将不起作用。
另一个猜测是你希望你的舍入取决于被舍入的数字的大小。以下功能可以在25到50,250到500,0.025到0.05和2500到5000之间。也许你可以在那里工作。
double round(double input)
{
double scale = Math.Floor(Math.Log10(input));
double step = 5 * Math.Pow(10, scale);
return step * Math.Ceiling(input/step);
}
答案 1 :(得分:1)
根据您的需要,这可能是一个不错的,可重复使用的解决方案。
static int RoundUpWeird(int rawNr)
{
if (rawNr < 100 && rawNr > -100)
return RoundUpToNext50(rawNr);
else
return RoundUpToNext500(rawNr);
}
static int RoundUpToNext50(int rawNr)
{
return RoundUpToNext(rawNr, 50);
}
static int RoundUpToNext500(int rawNr)
{
return RoundUpToNext(rawNr, 500);
}
static int RoundUpToNext(int rawNr, int next)
{
int result;
int remainder;
if ((remainder = rawNr % next) != 0)
{
if (rawNr >= 0)
result = RoundPositiveToNext(rawNr, next, remainder);
else
result = RoundNegativeToNext(rawNr, remainder);
if (result < rawNr)
throw new OverflowException("round(Number) > Int.MaxValue!");
return result;
}
return rawNr;
}
private static int RoundNegativeToNext(int rawNr, int remainder)
{
return rawNr - remainder;
}
private static int RoundPositiveToNext(int rawNr, int next, int remainder)
{
return rawNr + next - remainder;
}
答案 2 :(得分:0)
此代码应按照我可以收集的规则运行:
public static double Round(double val)
{
int baseNum = val <= 100 ? 100 : 1000;
double factor = 0.5;
double v = val / baseNum;
var res = Math.Ceiling(v / factor) / (1 / factor) * baseNum;
return res;
}
答案 3 :(得分:0)
这应该有效。还有比你写的更大的数字:
int round(int value)
{
int i = 1;
while (value > i)
{
i *= 10;
}
return (int)(0.05 * i * Math.Ceiling(value / (0.05 * i)));
}