21xrx.com
2025-04-14 14:42:35 Monday
文章检索 我的文章 写文章
C++语言编写计数问题程序
2023-06-27 07:29:00 深夜i     --     --
C++ 计数问题 程序 编写 算法

在日常生活中,我们经常会遇到需要计数的问题。例如,我们要统计一个班级里有多少名学生,或者需要统计一些商品的数量等等。这时,如果我们手动计算,不仅费时费力,而且还容易出错。因此,使用计算机程序来解决这些问题就很有必要了。本文将介绍如何使用C++语言编写一个计数问题程序。

首先,我们需要明确计数问题的类型。本文中,我们将关注两种类型的计数问题:整数计数和字符串计数。

整数计数是指统计一组整数中负数、正数和零的个数。例如,给定一组整数:-3, 6, 0, 7, -2,程序应该输出负数个数为2,正数个数为2,零的个数为1。下面是使用C++语言编写的解决方案:

#include <iostream>
using namespace std;
int main() {
  int N;
  int positive_count = 0;
  int negative_count = 0;
  int zero_count = 0;
  cout << "请输入整数的个数:" << endl;
  cin >> N;
  int a[N];  // 定义一个整形数组,用于存储N个整数
  cout << "请输入" << N << "个整数:" << endl;
  // 读入N个整数
  for(int i = 0; i < N; i++) {
    cin >> a[i];
    if(a[i] > 0)
      positive_count++;
    else if(a[i] < 0)
      negative_count++;
    else
      zero_count++;
  }
  cout << "正数个数为:" << positive_count << endl;
  cout << "负数个数为:" << negative_count << endl;
  cout << "零的个数为:" << zero_count << endl;
  return 0;
}

字符串计数是指统计一段字符串中字母、数字和空格的个数。下面是使用C++语言编写的解决方案:

#include <iostream>
using namespace std;
int main() {
  string str;
  int char_count = 0;
  int digit_count = 0;
  int space_count = 0;
  cout << "请输入一段字符串:" << endl;
  getline(cin, str);
  // 统计字符、数字和空格的个数
  for(int i = 0; i < str.length(); i++) {
    if(isalpha(str[i]))
      char_count++;
    else if(isdigit(str[i]))
      digit_count++;
    else if(str[i] == ' ')
      space_count++;
  }
  cout << "字母个数为:" << char_count << endl;
  cout << "数字个数为:" << digit_count << endl;
  cout << "空格个数为:" << space_count << endl;
  return 0;
}

总结来说,C++语言编写计数问题程序并不难,只需要使用数组、字符串和循环等基本语法,加上一些判断语句,就可以有效地解决计数问题。 如果想更深入学习计算机编程,可以继续学习更高级的算法和数据结构等内容。

  
  

评论区