长期存储百分比的问题

时间:2011-12-04 21:03:22

标签: java

我正在尝试为类编写一个程序,该程序从.txt文件中读取每年工作的小时数列表,分配/读取(在适当的术语上有点模糊:))将它们放入数组中,然后计算超额和打印它们。

运行时,控制台输出如下:

Employee 1 worked 1600 hours, an under-run of 160 or 0%
Employee 3 worked 1680 hours, an under-run of 80 or 0%

为什么百分比为零?

import java.io.*;
import javax.swing.*;

class Calculator 
{
 public static void main(String args[])
  {

  try{

      String filePathString=JOptionPane.showInputDialog(null,"What is the file path?");  

      FileInputStream fstream = new FileInputStream("C:\\hello.txt");
      BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
      String strLine;
      int counter = 0;
      long[] Array = new long[5];   


      //Read File Line By Line
      while (counter <= 4)

        {
            strLine = br.readLine();
            Array[counter] = Long.parseLong(strLine); 
            OverageUnderage(Array[counter], counter);
            counter = counter + 1;
        }

  //Close the input stream
  in.close();

    }

  catch (Exception e){//Catch exception if any
  System.err.println("Error: " + e.getMessage());
  }
  }

 public static long OverageUnderage(long hours, long counter)
 {
 long overageAmount = 0;
 long overagePercent = 0;

     if (hours < 1760)
     {    
        overageAmount = 1760 - hours;
        overagePercent = ((overageAmount/1760)*100);

        System.out.println("Employee "+counter+" worked "+hours+" hours, an under-run of "+overageAmount+" or "+overagePercent+"%");
    }

    return counter;
 }

}

4 个答案:

答案 0 :(得分:6)

数字( overageAmount / 1760 )被视为一个长期而非双倍的,您需要它。尝试:

overagePercent = ( ( overageAmount / 1760.0 ) * 100 );

使用1760上的.0会将其视为decmial值。这样可以防止您看到的舍入到0问题,并允许计算在其余计算中包含小数,从而为您提供所需的结果。

答案 1 :(得分:3)

这就是为什么(恕我直言)你划分长而不是双打:

overagePercent = ((overageAmount / 1760)*100);

此处overageAmount/1760返回 0
所以你有两个解决方案:

  1. 首先将overageAmount转换为double,然后执行操作
  2. 除以浮点1760.0,因此产生的数字已经是浮点数

答案 2 :(得分:1)

执行计算的顺序很重要,尤其是int值。

而不是

overagePercent = overageAmount / 1760 * 100;

可能是0 * 100或0你可以做

overagePercent = overageAmount * 100 / 1760;

这可能仍为0,但仅在答案小于1时才会出现。

答案 3 :(得分:0)

如果您需要以小数形式获得答案,则必须使用double或decimal。 你不能使用Long来表示整数。