Java printf求和和

时间:2016-05-11 00:00:43

标签: java printf

这就是我所拥有的:

  double[] miles = new double [10];

  double milesPerWeek = 26.0 / 10;
  double totalMiles = 0;
  double sum = 0;
  double average = 0;

  System.out.println("Week\tMiles");

  for (int i = 0; i < miles.length; i++){

     miles[i] += milesPerWeek;
     totalMiles += miles[i];

     System.out.printf("Week %d\t%.1f%n", i + 1, totalMiles);
  }
  for (int i = 0; i < miles.length; i++)
  {              
     sum = sum + miles[i];
     average = sum / miles.length;
  }
  System.out.printf("The total of miles run is: %.1f%n" + sum + "\n");

  System.out.printf("The average of miles run is: %.1f%n" + average);

这是我和sum和average的问题。我似乎无法使用print f格式化小数位而没有此错误消息:      运行的总里程数为:线程“main”中的异常java.util.MissingFormatArgumentException:格式说明符'%。1f'

请你指点我,因为我需要一个小数位。

3 个答案:

答案 0 :(得分:4)

您需要将值作为参数传递,而不是将它们连接起来:

package main

import (
  "testing"
)

var (
  addCorsBefore = addCors
  checkAPIKeyBefore = checkAPIKey
)

func clearMiddleware() {
  addCors = func(h http.Handler) http.Handler {
    return h
  }
  checkAPIKey = func(h http.Handler) http.Handler {
    return h
  }
}

func restoreMiddleware() {
  addCors = addCorsBefore
  checkAPIKey = checkAPIKeyBefore
}

func TestXYZHandler(t *testing.T) {

  clearMiddleware()

  // arrange, test, assert, etc.
  //

  restoreMiddleware()
}

答案 1 :(得分:0)

System.out.printf("The total of miles run is: %.1f%n\n", sum);

System.out.printf("The average of miles run is: %.1f%n", average);

答案 2 :(得分:0)

你知道那个时候有一个啊哈!我只是拥有它...加号不会用于形成你的输出......逗号是! 更正语法:

System.out.printf("The total of miles run is: %.1f%n", sum, "\n");

System.out.printf("The average of miles run is: %.1f%n", average);