题目:统计正整数和负整数的个数
编写一个C++程序,程序将提示用户输入一系列整数(输入0表示结束输入),然后统计并输出输入的正整数和负整数的个数。
要求:
- 程序开始运行时,输出提示信息:"Please enter some integers(enter 0 to quit):"。
- 用户输入一系列整数,每输入一个整数后程序进行判断:
- 如果输入的整数大于0,则正整数计数器加1。
- 如果输入的整数小于0,则负整数计数器加1。
- 输入0时,结束输入过程。
- 输入结束后,程序输出正整数的个数和负整数的个数,格式如下:
- "Count of positive integers : [正整数个数]"
- "Count of negetive integers : [负整数个数]"
源代码:
#include <iostream> // 包含输入输出流库
using namespace std;int main() {int i = 0, j = 0, n; // 初始化正整数计数器i为0,负整数计数器j为0,读入的整数n未初始化 cout << "Please enter some integers(enter 0 to quit):" << endl;// 输出提示信息,提示用户输入一系列整数,输入0结束 cin >> n; // 读入第一个整数n while (n != 0) { // 当读入的整数n不是0时,继续循环 if (n > 0) i++; // 如果n是正整数,正整数计数器i加1 if (n < 0) j++; // 如果n是负整数,负整数计数器j加1 cin >> n; // 读入下一个整数n }cout << "Count of positive integers :" << i << endl;// 输出正整数的个数 cout << "Count of negetive integers :" << j << endl;// 输出负整数的个数 return 0; // 程序结束,返回0表示成功
}
运行截图: