簡體   English   中英

我的Java程序中的邏輯錯誤

[英]Logic Error within my Java program

我只是在慢慢學習Java,而其中一項練習卻遇到了問題。 該程序將接受任何分鍾數的用戶輸入(我使用的示例是1000000000),然后該程序將查找剩余的年數和天數。 由於某種原因,我可以將正確的年數設為19,但是我對上一個語句的邏輯不正確,並且我沒有得到214天。

以下是我的程序代碼,如果您可以讓我理解為什么我沒有看到正確的答案,請告訴我。 另外,我不知道這本書是否寫錯了,但是它顯示的實際年數是1902年,但僅給出10億分鍾,就不可能獲得1902年。 那也是一個混亂。 感謝您提前的所有答復。

import java.util.Scanner;

public class NumberOFYears 
{
    public static void main(String[] args) 
    {
        //Create a Scanner object
        Scanner input = new Scanner(System.in);

        //Prompt user for input
        System.out.print("Please enter number of minutes:");
        int totalMinutes = input.nextInt();

        //Find the number of hours
        int totalHours = totalMinutes / 60;

        //Find the number of days
        int totalDays = totalHours / 24;

        //Find the number of years
        int totalYears = totalDays / 365;

        //Find the number of days left 
        int remainingDays = totalHours % 24;
        System.out.println(remainingDays);

    }
}

您正在計算剩余天數,因此請使用以下方法:

int remainingDays = totalDays % 365;

一旦知道了總數,就可以將剩余天數計算為

remainingDays = totalDays - 365 * totalYears;

您也可以使用模運算符。 當然,您的簡單代碼會忽略leap年……

順便說一句, 1,000,000,000 / (60 * 24 * 365)的確是1902 ,並且

1,000,000,000 / (60 * 24) - 365 * 1902 = 214

您可能要使用

int remainingDays = totalDays%365;

代替。 %是模運算符,它返回的余數小於右操作數

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM