2014年7月11日 星期五

java程式設計題目---日期處理【判斷星期(蔡勒公式法)】

在蔡勒演算法中,每一年被假設從3月開始,月份標號從3(3月)到14(二月),即1995年1月被認為是1994年13月。具體的演算法是這樣的:


蔡勒演算法






其中w代表星期

c代表世紀數減1(年份前兩位數)

y代表年(兩位數)

m代表月(m大於等於3,小於等於14,即在蔡勒公式中,某年的1、2月要看作上一年的13、14月來計算,比如2003年1月1日要看作2002年的13月1日來計算)

d代表日

[ ]稱作高斯符號,代表取整,即只要整數部份。
mod代表‎‎同餘‎(這裡代表括號裡除以7後的餘數)
//注:資料取自維基百科






  1. import java.util.Scanner;
  2.  
  3. public class C1
  4. {
  5. public static void main(String[] args)
  6. {
  7. Scanner input = new Scanner(System.in);
  8. //創建並提示使用者輸入年,月,日
  9. System.out.println("Enter year: (e.g. , 2012)");
  10. int a = input.nextInt(); //年
  11. System.out.println("Enter month: 1-12:");
  12. int m = input.nextInt(); //月
  13. System.out.println("Enter the day of month: 1-31:");
  14. int c= input.nextInt(); //日
  15. int q = c;
  16. //判斷是否為1月或2月,如果是,年數要減1
  17. if(m == 1 || m == 2)
  18. {
  19. a = a - 1;
  20. }
  21. //計算世紀與年份
  22. int j = a / 100; //世紀
  23. int k = a % 100; //年份
  24.  
  25. //計算m,1月為13月、2月為14月,其餘月份不變
  26. if( m == 1 )
  27. {
  28. m = 13;
  29. }
  30. if( m == 2)
  31. {
  32. m = 14;
  33. }
  34. if( 3 >= m || m <= 12 )
  35. {
  36. m = m;
  37. }
  38. //計算
  39. int d = 26 * ( m + 1 ) / 10;
  40. //計算剩公式剩餘部分
  41. int h = ( q + d + k + ( k /4 ) + ( j / 4 ) + ( 5 * j ) )% 7;
  42.  
  43. //判斷該日為星期幾
  44. if(h == 0)
  45. {
  46. System.out.println("Day of the week is Saturday");
  47. }
  48. if(h == 1)
  49. {
  50. System.out.println("Day of the week is Sunday");
  51. }
  52. if(h == 2)
  53. {
  54. System.out.println("Day of the week is Monday");
  55. }
  56. if(h == 3)
  57. {
  58. System.out.println("Day of the week is Tuesday");
  59. }
  60. if(h == 4)
  61. {
  62. System.out.println("Day of the week is Wednesday");
  63. }
  64. if(h == 5)
  65. {
  66. System.out.println("Day of the week is Thursday");
  67. }
  68. if(h == 6)
  69. {
  70. System.out.println("Day of the week is Friday");
  71. }
  72. }
  73. }

沒有留言:

張貼留言

Go(Golang)程式語言 設定GCC

下載MSYS2:  https://www.msys2.org/ 安裝 程式開始執行後輸入: pacman -Syu y y 在安裝目錄底下找到msys2.exe,雙擊執行 輸入指令: pacman -Su pacman -S --needed base-devel mingw-...