0

我的程序应该打印出这样的表格:

  Time          Fraction Since Midnight
     12:00 AM       0.0000
      1:00 AM       0.0417
      2:00 AM       0.0833
      3:00 AM       0.1250
      4:00 AM       0.1667
      5:00 AM       0.2083
      6:00 AM       0.2500
      7:00 AM       0.2917
      8:00 AM       0.3333
      9:00 AM       0.3750
     10:00 AM       0.4167
     11:00 AM       0.4583
     12:00 PM       0.5000
      1:00 PM       0.5417
      2:00 PM       0.5833
      3:00 PM       0.6250
      4:00 PM       0.6667
      5:00 PM       0.7083
      6:00 PM       0.7500
      7:00 PM       0.7917
      8:00 PM       0.8333
      9:00 PM       0.8750
     10:00 PM       0.9167
     11:00 PM       0.9583

它甚至可以编译,但是当我运行它时出现错误。我不知道如何解决它。这是我所拥有的:

public class FractionOfDay {
    static double frac = 0;
    static double timeSecs = 0;
    static int time = 0;

    public static void fractionOfDay( int hour, int minute, int second, char 
    half) {


    if (hour == 12 && minute == 0 && second == 0 && half == 'A') 
    {
      frac = 0.0000;
      System.out.printf("%8.4f", frac);

     }

        else if (half == 'A') {
          timeSecs = ((hour * 3600) + (minute * 60) + second);
          frac = (timeSecs / 86400);
          System.out.printf("%8.4f", frac);

    }
    else if (half == 'P') {
     timeSecs = ((hour * 3600) + (minute * 60) + second + (12 * 3600));
     frac = (timeSecs / 86400);
    System.out.printf("%f", frac);

    }

}

public static void main (String [] args) {
    int h = 12;
    double f12 = 0.0000;
    System.out.println("        Time     Fraction Since Midnight");
    System.out.printf("%8d:00 AM\n", h);
    for (int i = 1; i <= 11; i++) {
     System.out.printf("%8d:00 AM\n", i);
    }
    System.out.printf("%8d:00 PM\n", h);
    for (int i = 1; i <= 11; i++) {
     System.out.printf("%8d:00 PM\n", i);
    }

    System.out.printf("%8d:00 PM\n", f12);

     for (int i = 1; i <= 11; i++) {
     fractionOfDay(i, 0, 0, 'A');
    }

    for (int i = 1; i <= 11; i++) {
     fractionOfDay(i, 0, 0, 'P');
    }

}

}
4

4 回答 4

2

在您的主要方法中,您声明double f12 = 0.0000;了它,然后您调用System.out.printf("%8d:00 PM\n", f12);这将导致异常。

为了解决它,您可以将类型从double更改为int%dSystem.out.printf("%8d:00 PM\n", f12);int

于 2018-07-16T05:31:05.450 回答
1
System.out.printf("%8d:00 PM\n", f12);

f12是双精度数,因此它可以表示非整数小时数。这是什么意思,逻辑上?您可能不想打印

3.141592:00 PM

将类型更改f12int

于 2018-07-16T05:44:51.413 回答
1
 System.out.printf("%8d:00 PM\n", f12); 

%d 用于小数。但是你的论点是双精度型的。请看格式

将 %d 更改为 %s 以解决此问题 ->System.out.printf("%8s:00 PM\n", f12);

于 2018-07-16T05:32:35.897 回答
0

您可以将代码修改为此 -

System.out.printf("%.4f:00\n", f12);

还要声明 f12 如下 -

float f12 = 0.0000f;
于 2018-07-16T06:12:49.150 回答