問(wèn)題描述
我在顯示平均小數(shù)時(shí)遇到問(wèn)題.它一直顯示 0.00 或 0.1.我試著把它加倍,但我仍然得到相同的結(jié)果.另外,我想將我輸入的第一個(gè)整數(shù)包含在總和中,但我不知道如何.請(qǐng)幫助:
I have a problem in showing the decimals on the average. It keeps showing .00 or .1. I tried to put it in double, but I still get the same results.Also, I want to include the first integer that I input to the sum, but I have no idea how.Please help:
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("
Counter 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
,sum
和counter
變量是 int
,所以 Java 仍然使用 整數(shù)除法 在分配給 average
之前,例如5/10
結(jié)果是 0
而不是 0.5
.
Even if you declared average
to be double
, the sum
and counter
variables are int
, so Java still uses integer division before assigning it to average
, e.g. 5 / 10
results in 0
instead of 0.5
.
在除法之前將變量之一轉(zhuǎn)換為 double
以強(qiáng)制進(jìn)行浮點(diǎn)運(yùn)算:
Cast one of the variables to double
before the division to force a floating point operation:
double average;
...
average = (double) sum / counter;
您可以通過(guò)在進(jìn)入 while 循環(huán)之前對(duì)其進(jìn)行處理來(lái)將第一個(gè)數(shù)字包含在計(jì)算中(如果它不是標(biāo)記值).
You can include the first number in your calculation by processing it before you go into the while loop (if it's not the sentinel value).
這篇關(guān)于如何平均輸出小數(shù)?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!