倒数算法怎么做

时间:2018-07-05 14:31:24

标签: algorithm

我是编程的新手,在我们的编程课上,我们被要求做一种算法,该算法计算圣诞节给定日期之前的一天。我已经有了一个算法,但是它需要定义每个月圣诞节前的天数,然后定义许多if-else语句。我只是想知道是否有另一个更有效的算法来解决这个问题。我是用伪代码编写的。

这是我到目前为止所做的:

define jan=359, feb=328, mar=306, apr=269, may=239, jun=208, jul=178, aug=147, sep=116, oct=86, nov=55, dec=25

input mm
input dd

if mm is jan
     days= jan - dd
...

1 个答案:

答案 0 :(得分:0)

这是倒计时功能,

let dayMilli = (24*60*60*1000);
let hourMilli = (60*60*1000);
let minuteMilli = (60*1000);
let secondMilli = (1000);

function printTime(millis){
  var days = millis/dayMilli;
  var lessDay = millis % dayMilli;

  var hours = lessDay/hourMilli;
  var lessHour = lessDay % hourMilli;

  var minute = lessHour/minuteMilli;
  var lessMinute = lessHour % minuteMilli;

  var second = lessMinute / secondMilli;
  $("#myTime").text(parseInt(days) + " Days " + parseInt(hours) + " Hours " + parseInt(minute) + " Minutes " + parseInt(second) + " Seconds");

}

如果您需要倒数计时,可以尝试

//call every seconds the function update
var myVar = setInterval(update, 1000);

//date of christmas
var christmas = new Date(2018, 12, 25, 0, 0, 0, 0)

//update time difference
function update(){
  printTime(getTimeDif(christmas));
}

//get milliseconds difference from today to christmas 
function getTimeDif(dateBefore){
  return (dateBefore.getTime()- new Date()).getTime());
}