解题思路

这是一个数字统计问题,需要统计负数的个数和正整数的平均值。

关键点

  1. 输入规则:

    • 第一行输入整数个数 ()
    • 第二行输入 个整数,每个整数的绝对值不超过1000
    • 0不参与统计
  2. 输出要求:

    • 统计负数的个数
    • 计算所有正整数的平均值(保留一位小数)
    • 如果没有正数,则平均值输出0.0

代码

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    int n;
    while (cin >> n) {
        int negCount = 0;  // 负数个数
        int posCount = 0;  // 正数个数
        double posSum = 0; // 正数之和
        
        for (int i = 0; i < n; i++) {
            int num;
            cin >> num;
            if (num < 0) {
                negCount++;
            } else if (num > 0) {
                posCount++;
                posSum += num;
            }
        }
        
        cout << negCount << " ";
        if (posCount == 0) {
            cout << "0.0" << endl;
        } else {
            cout << fixed << setprecision(1) << posSum / posCount << endl;
        }
    }
    return 0;
}
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            int n = sc.nextInt();
            int negCount = 0;  // 负数个数
            int posCount = 0;  // 正数个数
            double posSum = 0; // 正数之和
            
            for (int i = 0; i < n; i++) {
                int num = sc.nextInt();
                if (num < 0) {
                    negCount++;
                } else if (num > 0) {
                    posCount++;
                    posSum += num;
                }
            }
            
            System.out.print(negCount + " ");
            if (posCount == 0) {
                System.out.println("0.0");
            } else {
                System.out.printf("%.1f%n", posSum / posCount);
            }
        }
    }
}
while True:
    try:
        n = int(input())
        nums = list(map(int, input().split()))
        
        neg_count = 0  # 负数个数
        pos_count = 0  # 正数个数
        pos_sum = 0    # 正数之和
        
        for num in nums:
            if num < 0:
                neg_count += 1
            elif num > 0:
                pos_count += 1
                pos_sum += num
        
        # 输出结果
        if pos_count == 0:
            print(f"{neg_count} 0.0")
        else:
            avg = pos_sum / pos_count
            print(f"{neg_count} {avg:.1f}")
            
    except:
        break

算法及复杂度

算法分析

  1. 统计过程:

    • 遍历输入的数字
    • 统计负数个数
    • 累加正数之和并统计正数个数
    • 计算正数平均值
  2. 输出处理:

    • 格式化输出,保留一位小数
    • 处理无正数的特殊情况

复杂度分析

  • 时间复杂度: - 其中 是输入的整数个数,只需要遍历一次
  • 空间复杂度: - 只需要几个变量来存储计数和求和结果