切断小数点

时间:2015-12-09 17:28:18

标签: java calculator

我如何格式化,以便在计算每小时里程后显示没有小数点?我根本不知道如何格式化。我目前得到的是它是四舍五入但它留下.0之后它看起来不正确。我还必须将其保留为double

import java.util.Scanner; 
import static java.lang.System.*;
import static java.lang.Math.*;

public class MilesPerHour {
  private int distance, hours, minutes;
  private double mph;

  public MilesPerHour() {
    setNums(0,0,0);
    mph = 0;
  }

  public MilesPerHour(int dist, int hrs, int mins) {
    distance = dist;
    hours = hrs;
    minutes = mins;
  }

  public void setNums(int dist, int hrs, int mins) {

  }

  public void calcMPH() {
    mph = Math.round((distance)/(hours + (minutes/60)));
  }

  public void print() {
    System.out.print(distance + " miles in " + hours + " hours and " + minutes + " minutes = " + mph + " MPH.");
  } 

  public static void main( String[] args ) {
    Scanner keyboard = new Scanner(in);
    out.print("Enter the distance :: ");
    int dist = keyboard.nextInt();
    out.print("Enter the hours :: ");
    int hrs = keyboard.nextInt();

    out.print("Enter the minutes :: ");
    int mins = keyboard.nextInt();

    MilesPerHour test = new MilesPerHour(dist, hrs, mins);
    test.calcMPH();
    test.print();
  }
}

2 个答案:

答案 0 :(得分:2)

您可以使用String.format()将双舍入显示为整数:

System.out.println("My number: " + String.format("%.0f", 2.5d));

将显示My number: 3

有关String格式化程序的语法,请参阅full documentation

答案 1 :(得分:1)

从你的代码:

private double mph;
即使您为mph分配了double的返回值,

Math.round()仍会保留System.out.print()。当您调用mph时,double被引用为System.out.print(" MPH: " + ((int)mph) ); ,导致尾随" .0"。

只需添加如下所示的类型转换:

#include "