How to output the decimal in average?(如何平均输出小数?)
问题描述
我在显示平均小数时遇到问题.它一直显示 0.00 或 0.1.我试着把它加倍,但我仍然得到相同的结果.另外,我想将我输入的第一个整数包含在总和中,但我不知道如何.请帮助:
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 仍然使用 整数除法 在分配给 average 之前,例如5/10 结果是 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.
在除法之前将变量之一转换为 double 以强制进行浮点运算:
Cast one of the variables to double before the division to force a floating point operation:
double average;
...
average = (double) sum / counter;
您可以通过在进入 while 循环之前对其进行处理来将第一个数字包含在计算中(如果它不是标记值).
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).
这篇关于如何平均输出小数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何平均输出小数?
基础教程推荐
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
- 将 Windows 证书导入 Java 2022-01-01
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- 在springboot中如何给mybatis加拦截器 2023-04-29
- 将 double 转换为 Int,向下舍入 2022-01-01
- Maven:无效的目标版本:10 2022-01-01
- JPA惰性列表上的流 2022-01-01
