牛客网 - 在线编程 - 华为机试 - 记录均正II

题目描述

从输入任意个整型数,统计其中的负数个数并求所有非负数的平均值

输入描述:

输入任意个整数

输出描述:

输出负数个数以及所有非负数的平均值

示例1

输入

-13
-4
-7

输出

3
0.0

c++:

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

int main()
{
	
	int n;
	int neg = 0;
	int pos = 0;
	double avg = 0;
	while (cin >> n)
	{
		if (n < 0)
		{
			neg++;
		}
		else
		{
			pos++;
			avg += n;
		}
		
	}
	cout << neg << endl;
	cout << setprecision(1) << fixed << avg / pos << endl;
	return 0;
}

python:

a = list(map(int, input().split()))
neg = 0;
no_neg = 0;
sum = 0;
for i in a:
    if i < 0:
        neg += 1
    else:
        no_neg += 1
        sum += i
print(neg)
print("%.1f" % (sum / no_neg))
            

最后一个print中sum/no_neg外要加括号

猜你喜欢

转载自blog.csdn.net/qq_39735236/article/details/81876608