如何确定一年的哪一天属于哪个月? [英] How to determine which day of a year belongs to what month?

查看:210
本文介绍了如何确定一年的哪一天属于哪个月?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名初学者,我必须在SML中编写一个函数。

I'm a beginner and I gotta write a function in SML.

赋值问题是:

The assignment question is :


编写一个名为<$ c $的函数c> what_month 将每天的数字(例如257,假定一年365天)作为输入,并返回当天所属的月份数。

write a function named what_month that takes the number of a day (e.g., 257, assuming 365 days a year) as input, and returns the number of the month, that this day belongs to.

示例: what_month(40)应返回 2 (二月)。

Example: what_month(40) should return 2 (February).


推荐答案

对于简单的情况(不包含闰年),您可以定义以$ months_days 和递归辅助函数 aux 为单位的天数列表,其中 int 称为 sum 和一个 int list 称为 numbers ,并返回一个 int n ,这样第一个 n 元素添加到 sum ,但第一个 n + 1 元素list添加到 sum 或更多。

for the simple case(that doesn't account for leap year), you can define a list of days in months months_days, and a recursive helper function aux, that takes an int called sum and an int list called numbers , and returns an int n such that the first n elements of the list add to less than sum, but the first n + 1 elements of the list add to sum or more.

val month_days= [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

fun what_month(day :int) =
 let  
   fun aux(sum :int,  numbers: int list) =
    let
      val numbers_tail = tl numbers
    in
      if sum <= (hd numbers)
      then 1
      else    
        1 + aux(sum, (hd numbers + hd numbers_tail)::(tl numbers_tail))
    end
 in
   aux(day, month_days)
 end

这篇关于如何确定一年的哪一天属于哪个月?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆