我正在根据一本教科书进行这个编程练习,其中给我们提供了一种计算星期几的算法,称为泽勒同余。那么你认为我可以获得与教科书中运行的示例相同的输出吗?它们与 2002 年第 3 个月和第 26 个月的某一天一致。样本会读回星期二。我已经进行了几个小时的修改和重写,但在周二之前却一事无成!
这是 Java 综合教科书 8e 的第 133 页,如果有人有的话...我是初学者,非常欢迎建设性的反馈!
您的建议将不胜感激:
import java.util.Scanner;
public class DayOfTheWeek {
public static void main(String[] args) {
// Set up the scanner...
Scanner input = new Scanner(System.in);
// Set up the day's of the week with 0 being Sat as per algorithm.
final String[] DAY_OF_WEEK = {"Saturday", "Sunday", "Monday",
"Tuesday", "Wednesday", "Thursday", "Friday"};
// Get the year
System.out.print("Enter the year (e.g., 2002): ");
int year = input.nextInt();
// Get the month
System.out.print("Enter the month 1-12: ");
int month = input.nextInt();
// Get the day
System.out.print("Enter the day 1-31: ");
int day = input.nextInt();
// According to the algorithm Jan is 13 & Feb 14...
if (month == 1) month = 13;
else if (month == 2) month = 14;
// j Is the century.
int j = year / 100;
// k Is the year of the century.
int k = year % 100 ;
// Calculate
double h = (month + ((26*(month + 1)) / 10) + k + (k / 4) +
(j / 4) + (5 * j)) % 7;
// Cast answer back to integer to get result from array
int ans = (int)h;
// Print result
System.out.println("Day of the week is: " + DAY_OF_WEEK[ans]);
}
}
最佳答案
看起来这行代码是错误的:
double h = (month + ((26*(month + 1)) / 10) + k + (k / 4) +
(j / 4) + (5 * j)) % 7;
该公式将日添加到第一个表达式中,而不是月。所以它应该看起来像这样:
double h = (day + ((26*(month + 1)) / 10) + k + (k / 4) +
(j / 4) + (5 * j)) % 7;
关于java - 星期几、java 和 Zeller 的同余!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6840020/