华为od机试:
输入一组整数,在[0,255]范围,输入小于0的数,取0;大于255的数取255
每个数加上一个数x
使得平均数最接近128,求这个数
Scanner sc = new Scanner(System.in);
List<Integer> list = new ArrayList<>();//保留输入的整数集合
int count = 0;
while (sc.hasNextInt()) {
int a = sc.nextInt();
if (a <= 0) {
a = 0;
}
if (a >= 255) {
a = 255;
}
list.add(a);
count++;
}
System.out.println("一组整数总个数:"+count);
int n = count;//总共多少个数
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class jiyas {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<Integer> list = new ArrayList<>();//保留输入的整数集合
int count = 0;
while (sc.hasNextInt()) {
int a = sc.nextInt();
if (a <= 0) {
a = 0;
}
if (a >= 255) {
a = 255;
}
list.add(a);
count++;
}
System.out.println("一组整数总个数:"+count);
int n = count;//总共多少个数
int flag=128;//要求的平均数128
int result = calculate(count, flag, list);//需要加的整数
System.out.println(result);
System.out.println("需要加的整数为"+result);
}
public static int calculate(int count,int flag,List<Integer> list){
int result=0;
//1.每个数和平均值作差
int chazhi=0;
for (Integer number:list) {
chazhi+=number-flag;//差值求和
}
//2.拿差值和0比较,
// =0的话,说明平均值刚好为128,加数0
// >0的话,说明平均值>128,则需要减数,总共需要减这个差值,分摊到每个数上就是 差值/个数
// <0的话,说明平均值<128,则需要加数,总共需要加这个差值,分摊到每个数上就是 差值/个数
if(chazhi==0){
return result;
}else{
//对小数四舍五入
result=Math.round(-(chazhi/ 5f));
}
return result;
}
}
想起小学一组数算平均数方法: