键盘输入一批数,输入零时结束,分别计算负数与正数的总和,最后输出结果.求源程序啊.
来源:学生作业帮助网 编辑:六六作业网 时间:2024/12/20 04:34:47
键盘输入一批数,输入零时结束,分别计算负数与正数的总和,最后输出结果.求源程序啊.
键盘输入一批数,输入零时结束,分别计算负数与正数的总和,最后输出结果.求源程序啊.
键盘输入一批数,输入零时结束,分别计算负数与正数的总和,最后输出结果.求源程序啊.
#include <malloc.h>
#include <string.h>
#include <math.h>
#define MAX(a, b) (a > b ? a : b)
#define MIN(a, b) (a < b ? a : b)
#define POSITIVE(a) (a > 0 ? 1 : 0)
#define NEGTIVE(a) (a < 0 ? 1 : 0)
int main()
{
printf("Input:\n");
int max_size = 128; // max size, can be extended
double *data = (double*) malloc(max_size * sizeof(double));// allocate memory
int num = 0;
while (1)
{
char szBuf[16];
memset(szBuf, 0, 16);
scanf("%s", szBuf);
if (0 == strcmp(szBuf, "over")) break;//input "over" as input over
data[num++] = atof(szBuf);
if (num == max_size) // extend memory
{
max_size *= 2;
data = (double*) realloc(data, max_size);
}
}
double max = data[0], min = data[0];
int posNum = 0, negNum = 0;
for (int i = 0; i < num; ++i)
{
max = MAX(max, data[i]);
min = MIN(min, data[i]);
posNum += POSITIVE(data[i]);
negNum += NEGTIVE(data[i]);
}
printf("\nOutput:\n");
printf("max: %f\nmin: %f\npositive num: %d\nnegtive num: %d\n",
max, min, posNum, negNum);
free(data); // free memory
return 0;
}
数据输入以“over”结束