我在平均顯示小數時出現問題。它一直顯示.00或.1。 我試圖把它上雙,但我仍然得到同樣的results.Also,我想包括第一個整數,我輸入的總和,但我不知道how.Please幫助:如何平均輸出小數?
import java.io.*;
import java.util.*;
public class WhileSentinelSum
{
static final int SENTINEL= -999;
public static void main(String[] args)
{
// Keyboard Initialization
Scanner kbin = new Scanner(System.in);
//Variable Initialization and Declaration
int number, counter;
int sum =0;
int average;
//Input
System.out.print("Enter an integer number: ");
number = kbin.nextInt();
counter=0;
//Processing
//Output
while(number != SENTINEL)
{
counter++;
System.out.print("Enter an integer number: ");
number = kbin.nextInt();
sum += number;
}
if (counter !=0)
System.out.println("\nCounter is: " + counter);
else
System.out.println("no input");
average= sum/counter;
System.out.println("The sum is " + sum);
System.out.println("The average is " + average);
System.out.println();
}//end main
}//end class
'average'必須是'double'。在平均分配時,做這個計算:'average =(sum + 0.0)/ counter;' – Justin 2013-04-03 22:07:36
看看這個:http:// stackoverflow。com/questions/2909451/java-simple-division-in-java-bug-feature – Justin 2013-04-03 22:11:04