C语言练习题:统计 N 个整数中,大于零或小于零的整数个数(数组)

2021/11/24 23:17:35

本文主要是介绍C语言练习题:统计 N 个整数中,大于零或小于零的整数个数(数组),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

实现函数,统计 N 个整数中,大于零或小于零的整数个数

函数定义

int count_plus_or_nega(int numbers[], int n, int plus_or_nega);

参数说明

  • numbers,待统计的整数数组
  • n,表示整数数组长度,且 n>=0
  • plus_or_nega,表示统计正数还是负数,当值为 1 时,表示统计正数个数,值为 0 时,表示统计负数个数

返回值

返回统计的个数

注意,零既不是正数,也不是负数

示例1

参数:

numbers = {-8, -9, 2, 5, -1, -4, 0}
n = 7
plus_or_nega = 1

返回

2
#include <stdio.h>

int count_plus_or_nega(int numbers[], int n, int plus_or_nega) {
    // TODO 请在此处编写代码,完成题目要求
    int j=0;
    for(int i=0;i<n;i++)
    {
        if(plus_or_nega==1&&numbers[i]>0)
            j++;
        else if(plus_or_nega==0&&numbers[i]<0) 
            j++;
    }
    return j;
}

int main () {
    int numbers[7] = {-8, -9, 2, 5, -1, -4, 0};
    int n = 7;
    int plus_or_nega = 1;
    int result = count_plus_or_nega(numbers,n,plus_or_nega);
    printf("%d",result);
    return 0;
}


这篇关于C语言练习题:统计 N 个整数中,大于零或小于零的整数个数(数组)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程