[Loops]D. Liang 4.2 Counting positive and negative number and computing the average of numbers.c

Description
Write a program that reads an unspecified number of integers, determines how many positive and negative values have been read, and computes the total and average of the input values (not counting zeros).
Your program ends with the input 0.
Display the average as a floating-point number with precision 2. (For example, if you entered 1, 2, and 0, the average should be 1.50.)
Input
Integers seperated by one blank, ends with 0.
Output
The count of positive number, the count of negative number, the total, and the average, each seperated by one blank. There is no space or a newline at the end.
Sample Input
1 2 0
Sample Output
2 0 3 1.50

***The combined usage of while and scanf:
在这里插入图片描述

common problem:

在这里插入图片描述This problem code as follow:

//  Date:2020/3/13
//  Author:xiezhg5 
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
    long int a=0;
    long int b=0;
    long int c1=0;
    long int num;
    long int t=0;
    double v=0;
    while(scanf("%ld",&num),num) //当读入的num为0时跳出循环 
    {
        if(num>0)
        {
            a++;       //a表示正数个数 
            t=t+num;  //正数和 
            c1++;     //c1计总数变量 
        }
        if(num<0)
        {
            b++;     //b表示负数个数 
            t=t+num;  //负数和 
            c1++;    //c1计负数变量 
        }
        
    }
    //非常重要的一个条件
	//防止除数为零程序错误情况 
    if(c1==0)
    {
    v=0;
    printf("%ld %ld %ld %.2lf\n",a,b,t,v);
    }
    else
    {
    	v=(double)(t)/(a+b);
    	printf("%ld %ld %ld %.2lf\n",a,b,t,v);
	}
    return 0;

}
发布了52 篇原创文章 · 获赞 25 · 访问量 1289

猜你喜欢

转载自blog.csdn.net/qq_45645641/article/details/104847823