Java写题解的第5天 | #记负均正#
记负均正
http://www.nowcoder.com/practice/6abde6ffcc354ea1a8333836bd6876b8
遍历输入并计算,通过率低的原因大概是很多没有考虑输入有0存在的情况吧。(确实第一眼看题目以为没有0输入)
代码于2022年7月9日更新:添加了对于正数个数为0的情况下的判断
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int n = sc.nextInt();
int countNegative = 0;
int countPositive = 0;
int sum = 0;
for (int i = 0; i < n; i++) {
int number = sc.nextInt();
if (number < 0) {
countNegative++;
} else if (number > 0){
sum += number;
countPositive++;
}
}
double average = countPositive == 0? 0.0 : sum * 1.0 / countPositive;
System.out.println(countNegative + " " + String.format("%.1f", average));
}
sc.close();
}
}