C/C++编程学习 - 第3周 ⑦ 数值统计

题目链接

题目描述

统计给定的n个数中,负数、零和正数的个数。

Input
输入数据有多组,每组占一行,每行的第一个数是整数 n(n < 100),表示需要统计的数值的个数,然后是 n 个实数;如果 n = 0,则表示输入结束,该行不做处理。

Output
对于每组输入数据,输出一行 a, b 和 c,分别表示给定的数据中负数、零和正数的个数。

Sample Input

6 0 1 2 3 -1 0
5 1 2 3 4 0.5
0 

Sample Output

1 2 3
0 0 5

思路

题意就是输入 n 个数,看有多少个数为正,多少个数为负,多少个数为零。如果 n = 0,则输入结束。可以写成while(~scanf("%d", &n) && n),也可以在循环中加上if(n == 0) break;

C语言代码:

#include<stdio.h>
int main()
{
    
    
	int a;
	while(~scanf("%d",&a) && a)
	{
    
    
		int zheng =0, fu = 0, ling = 0;
		for(int i = 0;i < a; i++)
		{
    
    
		    double x;
		    scanf("%lf",&x);
			if(x < 0) fu ++;
			if(x == 0) ling ++;
			if(x > 0) zheng ++;	
		} 
        printf("%d %d %d\n", fu, ling, zheng);
	}
	return 0;
}

C++代码:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    
    
	ios::sync_with_stdio(false);
	int n;
	double num;
	while(cin >> n)
	{
    
    
		if(n == 0) break;
		int a = 0, b = 0, c = 0;
		while(n--)
		{
    
    
			cin >> num;
			if(num > 0) a++;
			else if(num == 0) b++;
			else if(num < 0) c++;
		}
		cout << c << " " << b << " " << a << endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_44826711/article/details/112862995
今日推荐