C#如何把月份转换成季度
public int ConvertMonthToQuarter(int month){
double f = Convert.ToDouble(month)/3f;
if (f > Convert.ToInt32(f))
{
return Convert.ToInt32(f) + 1;
}
return Convert.ToInt32(f);
}
复制代码
欢迎路过的各位前来拍砖留言发表更简洁性能更高的算法,我会在第一时间更新到本文
转载请说明出处C#教程 --------------------编程问答--------------------
代码风格真差。还好意思来这里现眼。
就这么一个简单的函数,居然都不能把它实现得合格。基本的参数范围验证都没有,计算方法也低效。代码风格也差。
看我的:
--------------------编程问答-------------------- 顶楼上 --------------------编程问答-------------------- 再改进一下:
/// <summary>
/// Get quarter of the year by month value.
/// Notice: valid month range is [1 -- 12]
/// </summary>
/// <param name="month">month value.</param>
/// <returns>quarter value of the year</returns>
public int GetQuarterByMonth(int month)
{
if (month < 1 || month > 12)
{
string message = string.Format("Input parameter month ({0}) out of range[1 -- 12].", month);
throw new ArgumentOutOfRangeException("month", message);
}
int q = month / 3;
return q * 3 < month ? q + 1 : q;
}
--------------------编程问答--------------------
/// <summary>
/// Get quarter of the year by month value.
/// Notice: valid month range is [1 -- 12]
/// </summary>
/// <param name="month">month value.</param>
/// <returns>quarter value of the year</returns>
public int GetQuarterByMonth(int month)
{
if (month < 1 || month > 12)
{
string message = string.Format("Input parameter month ({0}) out of range[1 -- 12].", month);
throw new ArgumentOutOfRangeException("month", message);
}
return (month - 1) / 3 + 1;
}
精彩~
补充:.NET技术 , 非技术区