输入一个数字n,动态申请长度为n的数组,输入n个数字,分别求出这n个数字中正数、负数、零的个数。
示例输出
Input array size n:10
Input array:15 -2.5 2.9 3.1415 95 -45 0 15 -6.6 -50
Positive number:5
Negative number:4
Zero:1
参考程序模板:
int main()
{
int n;
int numP = 0, numN = 0, numZ = 0;
cout << "Input array size n:";
cin >> n;
// 动态申请长度为n的数组
cout << "Input array:";
// 输入数组中的元素
// TO DO: 判断正数、负数、零的个数
cout << "Positive number:" << numP << endl;
cout << "Negative number:" << numN << endl;
cout << "Zero:" << numZ << endl;
// TO DO: 释放空间
return 0;
}
int main()
{
int n;
int numP = 0, numN = 0, numZ = 0;
cout << "Input array size n:";
cin >> n;
// 动态申请长度为n的数组
double *arr = new double[n];
cout << "Input array:";
// 输入数组中的元素
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
// TO DO: 判断正数、负数、零的个数
for (int i = 0; i < n; i++)
{
if (arr[i] > 0)
numP++;
else if (arr[i] < 0)
numN++;
else
numZ++;
}
cout << "Positive number:" << numP << endl;
cout << "Negative number:" << numN << endl;
cout << "Zero:" << numZ << endl;
// TO DO: 释放空间
delete[] arr;
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int n;
int numP = 0, numN = 0, numZ = 0;
cout << "Input array size n:";
cin >> n;
// 动态申请长度为n的数组
double* buff = new double[n];
memset(buff,0.0,sizeof(double)*n);
cout << "Input array:";
// 输入数组中的元素
for (int i = 0;i < n;i++)
{
cin >> buff[i];
}
// TO DO: 判断正数、负数、零的个数
//Input array size n:10
//Input array:15 -2.5 2.9 3.1415 95 -45 0 15 -6.6 -50
for (int j = 0;j < n;j++)
{
if (buff[j] > 0)
{
numP++;
}
else if (buff[j] < 0)
{
numN++;
}
else
{
numZ++;
}
}
cout << "Positive number:" << numP << endl;
cout << "Negative number:" << numN << endl;
cout << "Zero:" << numZ << endl;
// TO DO: 释放空间
delete []buff;
buff = NULL;
system("pause");
return 0;
}
拿走不谢,记得点个采纳呀。