[英]Number of Days Conversion in Java
我需要使用模操作數將輸入的天數轉換為其等效的年/秒,月/秒,周/秒和天數。 我們昨天才開始討論,所以我還是有些生銹,但這是我制作的程序:
import java.util.Scanner;
public class DaysConvert {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int noOfDays, year, month, week, days;
System.out.print("Enter Number of Days: ");
noOfDays = input.nextInt();
year = noOfDays/365;
month = year%365;
week = month%30;
days = week%7;
System.out.println("Year: " + year);
System.out.println("Month: " + month);
System.out.println("Week: " + week);
System.out.println("Day: " + days);
}
}
我的算法有問題嗎?
如果您只打算在一年中的365 days
中固定一個月中的30 days
而沒有then年,那么您可以迭代到for循環中的天數,並從用戶輸入的內容中檢查每一天的模數。
樣品:
for(int i = 1; i < noOfDays+1; i++)
{
if((i %30) == 0)
month++;
if((i%7) == 0)
week++;
if((i%365) == 0)
++year;
if((i%1) == 0)
days++;
}
System.out.println("Year: " + year);
System.out.println("Month: " + month);
System.out.println("Week: " + week);
System.out.println("Days: " + days);
結果:
Enter Number of Days: 330
Year: 0
Month: 11
Week: 47
Days: 330
這將正常工作:
year = (double) (noOfDays/365);
month=noOfDays/30.41;
week=noOfDays/7;
我希望這有幫助。
像這樣做:
public class DaysConvert
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int noOfDays, year, month, week, days;
System.out.print("Enter Number of Days: ");
noOfDays = input.nextInt();
year = noOfDays/365;
noOfDays=noOfDays%365;
month = noOfDays/30;
noOfDays=noOfDays%30;
week = noOfDays/7;
noOfDays=noOfDays%7;
System.out.println("Year: " + year);
System.out.println("Month: " + month);
System.out.println("Week: " + week);
System.out.println("Day: " + noOfDays);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.