活动公告

系统通知
05-18 21:22
系统通知
通知:本站资源由网友上传分享,如有违规等问题请到版务模块进行投诉,资源失效请在帖子内回复要求补档,会尽快处理!
10-23 09:31

C++编程完全指南教你如何精确统计并高效输出数字的个数从基础语法到高级应用包含实际案例和代码示例助你快速掌握这一核心技能

SunJu_FaceMall

3万

主题

2860

科技点

3万

积分

白金月票

碾压王

积分
32872

塔罗立华奏

<font color=白金月票" /> 发表于 2025-9-11 19:00:01 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
引言

在C++编程中,统计并输出数字的个数是一项基础而重要的技能。无论是在数据分析、游戏开发、科学计算还是日常编程任务中,我们经常需要处理各种数字数据,并对其进行统计。本文将从基础语法开始,逐步深入到高级应用,通过详细的代码示例和实际案例,帮助读者全面掌握这一核心技能。

基础语法部分

基本数据类型和变量

在C++中,数字主要分为整数和浮点数两大类。整数类型包括int、short、long和long long,而浮点数类型包括float、double和long double。了解这些基本数据类型是统计数字的第一步。
  1. #include <iostream>
  2. int main() {
  3.     // 整数类型
  4.     int a = 10;
  5.     short b = 20;
  6.     long c = 30000;
  7.     long long d = 4000000000;
  8.    
  9.     // 浮点数类型
  10.     float e = 3.14f;
  11.     double f = 2.71828;
  12.     long double g = 1.618033988749895;
  13.    
  14.     // 输出这些数字
  15.     std::cout << "整数: " << a << ", " << b << ", " << c << ", " << d << std::endl;
  16.     std::cout << "浮点数: " << e << ", " << f << ", " << g << std::endl;
  17.    
  18.     return 0;
  19. }
复制代码

输入输出流

C++使用iostream库进行输入输出操作。std::cin用于输入,std::cout用于输出。下面是一个简单的例子,展示如何从用户输入中读取数字并输出:
  1. #include <iostream>
  2. int main() {
  3.     int number;
  4.     std::cout << "请输入一个整数: ";
  5.     std::cin >> number;
  6.     std::cout << "你输入的数字是: " << number << std::endl;
  7.    
  8.     return 0;
  9. }
复制代码

基本计数方法

最简单的数字统计方法是使用计数器变量。下面是一个示例,统计用户输入的数字个数:
  1. #include <iostream>
  2. int main() {
  3.     int count = 0;
  4.     int number;
  5.    
  6.     std::cout << "请输入一系列整数,以任意非数字字符结束: " << std::endl;
  7.    
  8.     while (std::cin >> number) {
  9.         count++;
  10.     }
  11.    
  12.     std::cout << "你输入了 " << count << " 个数字。" << std::endl;
  13.    
  14.     return 0;
  15. }
复制代码

在这个例子中,我们使用一个while循环和std::cin来读取用户输入的数字。每次成功读取一个数字,计数器count就会增加1。当用户输入非数字字符时,std::cin >> number会返回false,循环结束。

中级应用

数组中的数字统计

在实际编程中,我们经常需要统计数组中的数字个数。下面是一个示例,统计数组中特定数字的出现次数:
  1. #include <iostream>
  2. int main() {
  3.     int numbers[] = {1, 2, 3, 4, 5, 2, 3, 2, 1, 6, 7, 8, 2};
  4.     int size = sizeof(numbers) / sizeof(numbers[0]);
  5.     int target = 2;
  6.     int count = 0;
  7.    
  8.     for (int i = 0; i < size; i++) {
  9.         if (numbers[i] == target) {
  10.             count++;
  11.         }
  12.     }
  13.    
  14.     std::cout << "数字 " << target << " 在数组中出现了 " << count << " 次。" << std::endl;
  15.    
  16.     return 0;
  17. }
复制代码

如果我们想统计数组中所有数字的出现次数,可以使用一个映射(map)来存储每个数字及其出现次数:
  1. #include <iostream>
  2. #include <map>
  3. int main() {
  4.     int numbers[] = {1, 2, 3, 4, 5, 2, 3, 2, 1, 6, 7, 8, 2};
  5.     int size = sizeof(numbers) / sizeof(numbers[0]);
  6.     std::map<int, int> frequency;
  7.    
  8.     for (int i = 0; i < size; i++) {
  9.         frequency[numbers[i]]++;
  10.     }
  11.    
  12.     std::cout << "数字出现频率统计:" << std::endl;
  13.     for (const auto& pair : frequency) {
  14.         std::cout << pair.first << ": " << pair.second << " 次" << std::endl;
  15.     }
  16.    
  17.     return 0;
  18. }
复制代码

字符串中的数字统计

有时我们需要从字符串中提取并统计数字。下面是一个示例,统计字符串中的数字个数:
  1. #include <iostream>
  2. #include <string>
  3. #include <cctype>
  4. int main() {
  5.     std::string str = "abc123def456ghi789jkl";
  6.     int count = 0;
  7.    
  8.     for (char c : str) {
  9.         if (isdigit(c)) {
  10.             count++;
  11.         }
  12.     }
  13.    
  14.     std::cout << "字符串 "" << str << "" 中包含 " << count << " 个数字字符。" << std::endl;
  15.    
  16.     return 0;
  17. }
复制代码

如果我们想提取并统计字符串中的完整数字(而不仅仅是数字字符),可以使用更复杂的方法:
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <sstream>
  5. #include <map>
  6. int main() {
  7.     std::string str = "abc123def456ghi789jkl0mno42";
  8.     std::vector<int> numbers;
  9.     std::string currentNumber;
  10.    
  11.     for (char c : str) {
  12.         if (isdigit(c)) {
  13.             currentNumber += c;
  14.         } else if (!currentNumber.empty()) {
  15.             std::istringstream iss(currentNumber);
  16.             int number;
  17.             iss >> number;
  18.             numbers.push_back(number);
  19.             currentNumber.clear();
  20.         }
  21.     }
  22.    
  23.     // 处理字符串末尾的数字
  24.     if (!currentNumber.empty()) {
  25.         std::istringstream iss(currentNumber);
  26.         int number;
  27.         iss >> number;
  28.         numbers.push_back(number);
  29.     }
  30.    
  31.     std::cout << "从字符串中提取的数字: ";
  32.     for (int num : numbers) {
  33.         std::cout << num << " ";
  34.     }
  35.     std::cout << std::endl;
  36.    
  37.     std::cout << "共提取了 " << numbers.size() << " 个数字。" << std::endl;
  38.    
  39.     // 统计每个数字的出现频率
  40.     std::map<int, int> frequency;
  41.     for (int num : numbers) {
  42.         frequency[num]++;
  43.     }
  44.    
  45.     std::cout << "数字出现频率统计:" << std::endl;
  46.     for (const auto& pair : frequency) {
  47.         std::cout << pair.first << ": " << pair.second << " 次" << std::endl;
  48.     }
  49.    
  50.     return 0;
  51. }
复制代码

文件中的数字统计

在实际应用中,我们经常需要从文件中读取数据并统计数字。下面是一个示例,统计文本文件中的数字个数:
  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4. #include <vector>
  5. #include <sstream>
  6. int main() {
  7.     std::ifstream file("numbers.txt");
  8.     if (!file.is_open()) {
  9.         std::cerr << "无法打开文件" << std::endl;
  10.         return 1;
  11.     }
  12.    
  13.     std::vector<int> numbers;
  14.     std::string line;
  15.    
  16.     while (std::getline(file, line)) {
  17.         std::istringstream iss(line);
  18.         int number;
  19.         
  20.         while (iss >> number) {
  21.             numbers.push_back(number);
  22.         }
  23.     }
  24.    
  25.     file.close();
  26.    
  27.     std::cout << "从文件中读取的数字: ";
  28.     for (int num : numbers) {
  29.         std::cout << num << " ";
  30.     }
  31.     std::cout << std::endl;
  32.    
  33.     std::cout << "文件中共有 " << numbers.size() << " 个数字。" << std::endl;
  34.    
  35.     return 0;
  36. }
复制代码

如果我们想统计文件中每个数字的出现频率,可以使用以下代码:
  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4. #include <map>
  5. #include <sstream>
  6. int main() {
  7.     std::ifstream file("numbers.txt");
  8.     if (!file.is_open()) {
  9.         std::cerr << "无法打开文件" << std::endl;
  10.         return 1;
  11.     }
  12.    
  13.     std::map<int, int> frequency;
  14.     std::string line;
  15.    
  16.     while (std::getline(file, line)) {
  17.         std::istringstream iss(line);
  18.         int number;
  19.         
  20.         while (iss >> number) {
  21.             frequency[number]++;
  22.         }
  23.     }
  24.    
  25.     file.close();
  26.    
  27.     std::cout << "文件中数字出现频率统计:" << std::endl;
  28.     for (const auto& pair : frequency) {
  29.         std::cout << pair.first << ": " << pair.second << " 次" << std::endl;
  30.     }
  31.    
  32.     return 0;
  33. }
复制代码

高级应用

使用STL容器和算法

C++标准模板库(STL)提供了丰富的容器和算法,可以大大简化数字统计的任务。下面是一些使用STL进行数字统计的示例:
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <numeric>
  5. int main() {
  6.     std::vector<int> numbers = {1, 2, 3, 4, 5, 2, 3, 2, 1, 6, 7, 8, 2};
  7.    
  8.     // 统计特定数字的出现次数
  9.     int target = 2;
  10.     int count = std::count(numbers.begin(), numbers.end(), target);
  11.     std::cout << "数字 " << target << " 出现了 " << count << " 次。" << std::endl;
  12.    
  13.     // 计算所有数字的总和
  14.     int sum = std::accumulate(numbers.begin(), numbers.end(), 0);
  15.     std::cout << "所有数字的总和是: " << sum << std::endl;
  16.    
  17.     // 计算数字的平均值
  18.     double average = static_cast<double>(sum) / numbers.size();
  19.     std::cout << "数字的平均值是: " << average << std::endl;
  20.    
  21.     // 找出最大值和最小值
  22.     auto [minIt, maxIt] = std::minmax_element(numbers.begin(), numbers.end());
  23.     std::cout << "最小值: " << *minIt << ", 最大值: " << *maxIt << std::endl;
  24.    
  25.     return 0;
  26. }
复制代码
  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <algorithm>
  5. int main() {
  6.     std::vector<int> numbers = {1, 2, 3, 4, 5, 2, 3, 2, 1, 6, 7, 8, 2};
  7.     std::map<int, int> frequency;
  8.    
  9.     // 使用for_each和lambda表达式统计频率
  10.     std::for_each(numbers.begin(), numbers.end(),
  11.         [&frequency](int n) { frequency[n]++; });
  12.    
  13.     // 输出频率统计
  14.     std::cout << "数字出现频率统计:" << std::endl;
  15.     for (const auto& pair : frequency) {
  16.         std::cout << pair.first << ": " << pair.second << " 次" << std::endl;
  17.     }
  18.    
  19.     // 找出出现次数最多的数字
  20.     auto mostFrequent = std::max_element(frequency.begin(), frequency.end(),
  21.         [](const auto& a, const auto& b) { return a.second < b.second; });
  22.    
  23.     std::cout << "出现次数最多的数字是 " << mostFrequent->first
  24.               << ",出现了 " << mostFrequent->second << " 次。" << std::endl;
  25.    
  26.     return 0;
  27. }
复制代码
  1. #include <iostream>
  2. #include <vector>
  3. #include <unordered_map>
  4. #include <algorithm>
  5. int main() {
  6.     std::vector<int> numbers = {1, 2, 3, 4, 5, 2, 3, 2, 1, 6, 7, 8, 2};
  7.     std::unordered_map<int, int> frequency;
  8.    
  9.     // 统计频率
  10.     for (int num : numbers) {
  11.         frequency[num]++;
  12.     }
  13.    
  14.     // 输出频率统计
  15.     std::cout << "数字出现频率统计:" << std::endl;
  16.     for (const auto& pair : frequency) {
  17.         std::cout << pair.first << ": " << pair.second << " 次" << std::endl;
  18.     }
  19.    
  20.     // 按频率排序
  21.     std::vector<std::pair<int, int>> sortedFrequency(frequency.begin(), frequency.end());
  22.     std::sort(sortedFrequency.begin(), sortedFrequency.end(),
  23.         [](const auto& a, const auto& b) { return a.second > b.second; });
  24.    
  25.     // 输出排序后的频率统计
  26.     std::cout << "\n按频率排序后的统计:" << std::endl;
  27.     for (const auto& pair : sortedFrequency) {
  28.         std::cout << pair.first << ": " << pair.second << " 次" << std::endl;
  29.     }
  30.    
  31.     return 0;
  32. }
复制代码

多种数据类型的数字统计

在实际应用中,我们可能需要处理多种数据类型的数字。下面是一个示例,统计不同类型数字的出现次数:
  1. #include <iostream>
  2. #include <vector>
  3. #include <variant>
  4. #include <map>
  5. #include <string>
  6. #include <iomanip>
  7. // 使用std::variant来处理多种数字类型
  8. using NumberType = std::variant<int, float, double, long>;
  9. // 访问者模式,用于打印不同类型的数字
  10. struct PrintVisitor {
  11.     void operator()(int i) const { std::cout << i << " (int)"; }
  12.     void operator()(float f) const { std::cout << std::fixed << std::setprecision(2) << f << " (float)"; }
  13.     void operator()(double d) const { std::cout << std::fixed << std::setprecision(4) << d << " (double)"; }
  14.     void operator()(long l) const { std::cout << l << " (long)"; }
  15. };
  16. // 访问者模式,用于获取数字类型的字符串表示
  17. struct TypeVisitor {
  18.     std::string operator()(int) const { return "int"; }
  19.     std::string operator()(float) const { return "float"; }
  20.     std::string operator()(double) const { return "double"; }
  21.     std::string operator()(long) const { return "long"; }
  22. };
  23. int main() {
  24.     std::vector<NumberType> numbers = {
  25.         1, 2.5f, 3.14159, 4L, 5, 6.7f, 8.90123, 10L, 11, 12.3f
  26.     };
  27.    
  28.     // 按类型统计数字个数
  29.     std::map<std::string, int> typeCount;
  30.    
  31.     for (const auto& num : numbers) {
  32.         std::string type = std::visit(TypeVisitor{}, num);
  33.         typeCount[type]++;
  34.     }
  35.    
  36.     // 输出类型统计
  37.     std::cout << "按类型统计数字个数:" << std::endl;
  38.     for (const auto& pair : typeCount) {
  39.         std::cout << pair.first << ": " << pair.second << " 个" << std::endl;
  40.     }
  41.    
  42.     // 输出所有数字及其类型
  43.     std::cout << "\n所有数字及其类型:" << std::endl;
  44.     for (const auto& num : numbers) {
  45.         std::visit(PrintVisitor{}, num);
  46.         std::cout << std::endl;
  47.     }
  48.    
  49.     return 0;
  50. }
复制代码

性能优化技巧

在处理大量数据时,性能优化变得尤为重要。下面是一些优化数字统计性能的技巧:
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <execution>
  5. #include <chrono>
  6. #include <random>
  7. int main() {
  8.     // 生成大量随机数
  9.     const int size = 10000000;
  10.     std::vector<int> numbers(size);
  11.    
  12.     std::random_device rd;
  13.     std::mt19937 gen(rd());
  14.     std::uniform_int_distribution<> dis(1, 100);
  15.    
  16.     for (int i = 0; i < size; i++) {
  17.         numbers[i] = dis(gen);
  18.     }
  19.    
  20.     // 使用顺序算法统计特定数字的出现次数
  21.     int target = 42;
  22.     auto start = std::chrono::high_resolution_clock::now();
  23.     int countSeq = std::count(numbers.begin(), numbers.end(), target);
  24.     auto end = std::chrono::high_resolution_clock::now();
  25.     std::chrono::duration<double> seqTime = end - start;
  26.    
  27.     std::cout << "顺序算法结果: " << countSeq << std::endl;
  28.     std::cout << "顺序算法耗时: " << seqTime.count() << " 秒" << std::endl;
  29.    
  30.     // 使用并行算法统计特定数字的出现次数
  31.     start = std::chrono::high_resolution_clock::now();
  32.     int countPar = std::count(std::execution::par, numbers.begin(), numbers.end(), target);
  33.     end = std::chrono::high_resolution_clock::now();
  34.     std::chrono::duration<double> parTime = end - start;
  35.    
  36.     std::cout << "并行算法结果: " << countPar << std::endl;
  37.     std::cout << "并行算法耗时: " << parTime.count() << " 秒" << std::endl;
  38.    
  39.     std::cout << "并行算法比顺序算法快 " << (seqTime.count() / parTime.count()) << " 倍" << std::endl;
  40.    
  41.     return 0;
  42. }
复制代码
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <random>
  5. // 使用位运算统计特定数字的出现次数
  6. int countWithBitOps(const std::vector<int>& numbers, int target) {
  7.     int count = 0;
  8.     for (int num : numbers) {
  9.         // 使用异或运算和比较,避免分支预测
  10.         count += ((num ^ target) - 1) >> 31 & 1;
  11.     }
  12.     return count;
  13. }
  14. int main() {
  15.     // 生成大量随机数
  16.     const int size = 10000000;
  17.     std::vector<int> numbers(size);
  18.    
  19.     std::random_device rd;
  20.     std::mt19937 gen(rd());
  21.     std::uniform_int_distribution<> dis(1, 100);
  22.    
  23.     for (int i = 0; i < size; i++) {
  24.         numbers[i] = dis(gen);
  25.     }
  26.    
  27.     int target = 42;
  28.    
  29.     // 使用标准算法
  30.     auto start = std::chrono::high_resolution_clock::now();
  31.     int countStd = std::count(numbers.begin(), numbers.end(), target);
  32.     auto end = std::chrono::high_resolution_clock::now();
  33.     std::chrono::duration<double> stdTime = end - start;
  34.    
  35.     // 使用位运算优化
  36.     start = std::chrono::high_resolution_clock::now();
  37.     int countBit = countWithBitOps(numbers, target);
  38.     end = std::chrono::high_resolution_clock::now();
  39.     std::chrono::duration<double> bitTime = end - start;
  40.    
  41.     std::cout << "标准算法结果: " << countStd << std::endl;
  42.     std::cout << "标准算法耗时: " << stdTime.count() << " 秒" << std::endl;
  43.    
  44.     std::cout << "位运算算法结果: " << countBit << std::endl;
  45.     std::cout << "位运算算法耗时: " << bitTime.count() << " 秒" << std::endl;
  46.    
  47.     std::cout << "位运算算法比标准算法快 " << (stdTime.count() / bitTime.count()) << " 倍" << std::endl;
  48.    
  49.     return 0;
  50. }
复制代码
  1. #include <iostream>
  2. #include <vector>
  3. #include <unordered_map>
  4. #include <random>
  5. #include <chrono>
  6. // 使用连续内存的向量代替哈希表进行频率统计
  7. std::vector<int> countWithVector(const std::vector<int>& numbers, int maxVal) {
  8.     std::vector<int> frequency(maxVal + 1, 0);
  9.    
  10.     for (int num : numbers) {
  11.         if (num >= 0 && num <= maxVal) {
  12.             frequency[num]++;
  13.         }
  14.     }
  15.    
  16.     return frequency;
  17. }
  18. // 使用哈希表进行频率统计
  19. std::unordered_map<int, int> countWithUnorderedMap(const std::vector<int>& numbers) {
  20.     std::unordered_map<int, int> frequency;
  21.    
  22.     for (int num : numbers) {
  23.         frequency[num]++;
  24.     }
  25.    
  26.     return frequency;
  27. }
  28. int main() {
  29.     // 生成大量随机数
  30.     const int size = 10000000;
  31.     std::vector<int> numbers(size);
  32.    
  33.     std::random_device rd;
  34.     std::mt19937 gen(rd());
  35.     std::uniform_int_distribution<> dis(1, 1000);
  36.    
  37.     for (int i = 0; i < size; i++) {
  38.         numbers[i] = dis(gen);
  39.     }
  40.    
  41.     // 使用向量进行频率统计
  42.     auto start = std::chrono::high_resolution_clock::now();
  43.     auto frequencyVec = countWithVector(numbers, 1000);
  44.     auto end = std::chrono::high_resolution_clock::now();
  45.     std::chrono::duration<double> vecTime = end - start;
  46.    
  47.     // 使用哈希表进行频率统计
  48.     start = std::chrono::high_resolution_clock::now();
  49.     auto frequencyMap = countWithUnorderedMap(numbers);
  50.     end = std::chrono::high_resolution_clock::now();
  51.     std::chrono::duration<double> mapTime = end - start;
  52.    
  53.     std::cout << "向量统计耗时: " << vecTime.count() << " 秒" << std::endl;
  54.     std::cout << "哈希表统计耗时: " << mapTime.count() << " 秒" << std::endl;
  55.    
  56.     std::cout << "向量统计比哈希表统计快 " << (mapTime.count() / vecTime.count()) << " 倍" << std::endl;
  57.    
  58.     return 0;
  59. }
复制代码

实际案例分析

数据分析中的数字统计

在数据分析中,我们经常需要统计各种数字指标,如平均值、中位数、众数等。下面是一个示例,展示如何使用C++进行基本的数据分析:
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <numeric>
  5. #include <map>
  6. #include <iomanip>
  7. #include <random>
  8. class DataAnalyzer {
  9. private:
  10.     std::vector<double> data;
  11.    
  12. public:
  13.     DataAnalyzer(const std::vector<double>& input) : data(input) {}
  14.    
  15.     // 计算平均值
  16.     double mean() const {
  17.         if (data.empty()) return 0.0;
  18.         return std::accumulate(data.begin(), data.end(), 0.0) / data.size();
  19.     }
  20.    
  21.     // 计算中位数
  22.     double median() {
  23.         if (data.empty()) return 0.0;
  24.         
  25.         std::sort(data.begin(), data.end());
  26.         
  27.         size_t size = data.size();
  28.         if (size % 2 == 0) {
  29.             return (data[size/2 - 1] + data[size/2]) / 2.0;
  30.         } else {
  31.             return data[size/2];
  32.         }
  33.     }
  34.    
  35.     // 计算众数
  36.     std::vector<double> modes() {
  37.         if (data.empty()) return {};
  38.         
  39.         std::map<double, int> frequency;
  40.         for (double value : data) {
  41.             frequency[value]++;
  42.         }
  43.         
  44.         int maxFreq = 0;
  45.         for (const auto& pair : frequency) {
  46.             if (pair.second > maxFreq) {
  47.                 maxFreq = pair.second;
  48.             }
  49.         }
  50.         
  51.         std::vector<double> result;
  52.         for (const auto& pair : frequency) {
  53.             if (pair.second == maxFreq) {
  54.                 result.push_back(pair.first);
  55.             }
  56.         }
  57.         
  58.         return result;
  59.     }
  60.    
  61.     // 计算标准差
  62.     double standardDeviation() const {
  63.         if (data.size() < 2) return 0.0;
  64.         
  65.         double m = mean();
  66.         double sqSum = std::inner_product(data.begin(), data.end(), data.begin(), 0.0);
  67.         return std::sqrt(sqSum / data.size() - m * m);
  68.     }
  69.    
  70.     // 计算四分位数
  71.     std::vector<double> quartiles() {
  72.         if (data.empty()) return {0.0, 0.0, 0.0};
  73.         
  74.         std::sort(data.begin(), data.end());
  75.         
  76.         size_t n = data.size();
  77.         double q1, q2, q3;
  78.         
  79.         // 计算Q2(中位数)
  80.         if (n % 2 == 0) {
  81.             q2 = (data[n/2 - 1] + data[n/2]) / 2.0;
  82.         } else {
  83.             q2 = data[n/2];
  84.         }
  85.         
  86.         // 计算Q1
  87.         size_t m = n / 2;
  88.         if (m % 2 == 0) {
  89.             q1 = (data[m/2 - 1] + data[m/2]) / 2.0;
  90.         } else {
  91.             q1 = data[m/2];
  92.         }
  93.         
  94.         // 计算Q3
  95.         if (n % 2 == 0) {
  96.             if (m % 2 == 0) {
  97.                 q3 = (data[m + m/2 - 1] + data[m + m/2]) / 2.0;
  98.             } else {
  99.                 q3 = data[m + m/2];
  100.             }
  101.         } else {
  102.             if (m % 2 == 0) {
  103.                 q3 = (data[m + 1 + m/2 - 1] + data[m + 1 + m/2]) / 2.0;
  104.             } else {
  105.                 q3 = data[m + 1 + m/2];
  106.             }
  107.         }
  108.         
  109.         return {q1, q2, q3};
  110.     }
  111.    
  112.     // 生成统计报告
  113.     void generateReport() {
  114.         std::cout << std::fixed << std::setprecision(2);
  115.         std::cout << "数据统计报告:" << std::endl;
  116.         std::cout << "--------------------------------" << std::endl;
  117.         std::cout << "数据点数量: " << data.size() << std::endl;
  118.         std::cout << "平均值: " << mean() << std::endl;
  119.         std::cout << "中位数: " << median() << std::endl;
  120.         
  121.         auto modeValues = modes();
  122.         if (modeValues.size() == 1) {
  123.             std::cout << "众数: " << modeValues[0] << std::endl;
  124.         } else {
  125.             std::cout << "众数: ";
  126.             for (size_t i = 0; i < modeValues.size(); i++) {
  127.                 if (i > 0) std::cout << ", ";
  128.                 std::cout << modeValues[i];
  129.             }
  130.             std::cout << std::endl;
  131.         }
  132.         
  133.         std::cout << "标准差: " << standardDeviation() << std::endl;
  134.         
  135.         auto qs = quartiles();
  136.         std::cout << "四分位数: Q1=" << qs[0] << ", Q2=" << qs[1] << ", Q3=" << qs[2] << std::endl;
  137.         std::cout << "--------------------------------" << std::endl;
  138.     }
  139. };
  140. int main() {
  141.     // 生成随机数据
  142.     const int size = 100;
  143.     std::vector<double> data(size);
  144.    
  145.     std::random_device rd;
  146.     std::mt19937 gen(rd());
  147.     std::normal_distribution<> dist(50.0, 15.0); // 正态分布,均值50,标准差15
  148.    
  149.     for (int i = 0; i < size; i++) {
  150.         data[i] = dist(gen);
  151.     }
  152.    
  153.     // 创建数据分析器并生成报告
  154.     DataAnalyzer analyzer(data);
  155.     analyzer.generateReport();
  156.    
  157.     return 0;
  158. }
复制代码

游戏开发中的数字统计

在游戏开发中,数字统计可以用于各种目的,如计分、统计玩家行为、分析游戏数据等。下面是一个简单的游戏统计系统示例:
  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <string>
  5. #include <algorithm>
  6. #include <random>
  7. #include <ctime>
  8. class GameStats {
  9. private:
  10.     std::map<std::string, int> playerScores;
  11.     std::map<int, int> levelCompletionTimes; // 关卡ID -> 完成时间(秒)
  12.     std::map<std::string, int> itemUsage; // 物品名称 -> 使用次数
  13.     std::vector<int> dailyActivePlayers; // 每日活跃玩家数
  14.    
  15. public:
  16.     // 添加玩家分数
  17.     void addPlayerScore(const std::string& playerName, int score) {
  18.         playerScores[playerName] += score;
  19.     }
  20.    
  21.     // 记录关卡完成时间
  22.     void recordLevelCompletion(int levelId, int timeInSeconds) {
  23.         levelCompletionTimes[levelId] = timeInSeconds;
  24.     }
  25.    
  26.     // 记录物品使用
  27.     void recordItemUsage(const std::string& itemName) {
  28.         itemUsage[itemName]++;
  29.     }
  30.    
  31.     // 记录每日活跃玩家数
  32.     void recordDailyActivePlayers(int count) {
  33.         dailyActivePlayers.push_back(count);
  34.     }
  35.    
  36.     // 获取排行榜
  37.     std::vector<std::pair<std::string, int>> getLeaderboard(int topN = 10) {
  38.         std::vector<std::pair<std::string, int>> sortedPlayers(
  39.             playerScores.begin(), playerScores.end());
  40.         
  41.         std::sort(sortedPlayers.begin(), sortedPlayers.end(),
  42.             [](const auto& a, const auto& b) { return a.second > b.second; });
  43.         
  44.         if (sortedPlayers.size() > static_cast<size_t>(topN)) {
  45.             sortedPlayers.resize(topN);
  46.         }
  47.         
  48.         return sortedPlayers;
  49.     }
  50.    
  51.     // 获取平均关卡完成时间
  52.     double getAverageLevelCompletionTime() const {
  53.         if (levelCompletionTimes.empty()) return 0.0;
  54.         
  55.         double sum = 0.0;
  56.         for (const auto& pair : levelCompletionTimes) {
  57.             sum += pair.second;
  58.         }
  59.         
  60.         return sum / levelCompletionTimes.size();
  61.     }
  62.    
  63.     // 获取最常用的物品
  64.     std::vector<std::pair<std::string, int>> getMostUsedItems(int topN = 5) {
  65.         std::vector<std::pair<std::string, int>> sortedItems(
  66.             itemUsage.begin(), itemUsage.end());
  67.         
  68.         std::sort(sortedItems.begin(), sortedItems.end(),
  69.             [](const auto& a, const auto& b) { return a.second > b.second; });
  70.         
  71.         if (sortedItems.size() > static_cast<size_t>(topN)) {
  72.             sortedItems.resize(topN);
  73.         }
  74.         
  75.         return sortedItems;
  76.     }
  77.    
  78.     // 获取平均每日活跃玩家数
  79.     double getAverageDailyActivePlayers() const {
  80.         if (dailyActivePlayers.empty()) return 0.0;
  81.         
  82.         double sum = 0.0;
  83.         for (int count : dailyActivePlayers) {
  84.             sum += count;
  85.         }
  86.         
  87.         return sum / dailyActivePlayers.size();
  88.     }
  89.    
  90.     // 生成统计报告
  91.     void generateReport() {
  92.         std::cout << "游戏统计报告" << std::endl;
  93.         std::cout << "==========================" << std::endl;
  94.         
  95.         // 排行榜
  96.         std::cout << "\n玩家排行榜 (前5名):" << std::endl;
  97.         auto leaderboard = getLeaderboard(5);
  98.         for (size_t i = 0; i < leaderboard.size(); i++) {
  99.             std::cout << (i+1) << ". " << leaderboard[i].first
  100.                       << ": " << leaderboard[i].second << " 分" << std::endl;
  101.         }
  102.         
  103.         // 关卡完成时间
  104.         std::cout << "\n关卡统计:" << std::endl;
  105.         std::cout << "平均关卡完成时间: " << getAverageLevelCompletionTime() << " 秒" << std::endl;
  106.         std::cout << "总关卡数: " << levelCompletionTimes.size() << std::endl;
  107.         
  108.         // 物品使用
  109.         std::cout << "\n最常用物品 (前3名):" << std::endl;
  110.         auto topItems = getMostUsedItems(3);
  111.         for (size_t i = 0; i < topItems.size(); i++) {
  112.             std::cout << (i+1) << ". " << topItems[i].first
  113.                       << ": " << topItems[i].second << " 次" << std::endl;
  114.         }
  115.         
  116.         // 每日活跃玩家
  117.         std::cout << "\n玩家活跃度:" << std::endl;
  118.         std::cout << "平均每日活跃玩家数: " << getAverageDailyActivePlayers() << std::endl;
  119.         std::cout << "记录天数: " << dailyActivePlayers.size() << std::endl;
  120.         
  121.         std::cout << "\n==========================" << std::endl;
  122.     }
  123. };
  124. int main() {
  125.     // 创建游戏统计对象
  126.     GameStats stats;
  127.    
  128.     // 模拟游戏数据
  129.     std::vector<std::string> playerNames = {"Alice", "Bob", "Charlie", "David", "Eve", "Frank", "Grace"};
  130.     std::vector<std::string> itemNames = {"Health Potion", "Mana Potion", "Sword", "Shield", "Bow"};
  131.    
  132.     std::random_device rd;
  133.     std::mt19937 gen(rd());
  134.    
  135.     // 模拟玩家分数
  136.     std::uniform_int_distribution<> scoreDist(100, 1000);
  137.     for (int i = 0; i < 50; i++) {
  138.         std::string player = playerNames[gen() % playerNames.size()];
  139.         int score = scoreDist(gen);
  140.         stats.addPlayerScore(player, score);
  141.     }
  142.    
  143.     // 模拟关卡完成时间
  144.     std::uniform_int_distribution<> levelDist(1, 10);
  145.     std::uniform_int_distribution<> timeDist(60, 600);
  146.     for (int i = 0; i < 30; i++) {
  147.         int level = levelDist(gen);
  148.         int time = timeDist(gen);
  149.         stats.recordLevelCompletion(level, time);
  150.     }
  151.    
  152.     // 模拟物品使用
  153.     std::uniform_int_distribution<> itemDist(0, itemNames.size() - 1);
  154.     for (int i = 0; i < 100; i++) {
  155.         std::string item = itemNames[itemDist(gen)];
  156.         stats.recordItemUsage(item);
  157.     }
  158.    
  159.     // 模拟每日活跃玩家
  160.     std::uniform_int_distribution<> playerDist(50, 200);
  161.     for (int i = 0; i < 30; i++) {
  162.         int count = playerDist(gen);
  163.         stats.recordDailyActivePlayers(count);
  164.     }
  165.    
  166.     // 生成统计报告
  167.     stats.generateReport();
  168.    
  169.     return 0;
  170. }
复制代码

科学计算中的数字统计

在科学计算中,数字统计是数据分析的基础。下面是一个示例,展示如何使用C++进行科学数据的统计分析:
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <numeric>
  5. #include <cmath>
  6. #include <iomanip>
  7. #include <random>
  8. class ScientificDataAnalyzer {
  9. private:
  10.     std::vector<double> data;
  11.    
  12. public:
  13.     ScientificDataAnalyzer(const std::vector<double>& input) : data(input) {}
  14.    
  15.     // 基本统计量
  16.     double mean() const {
  17.         if (data.empty()) return 0.0;
  18.         return std::accumulate(data.begin(), data.end(), 0.0) / data.size();
  19.     }
  20.    
  21.     double median() {
  22.         if (data.empty()) return 0.0;
  23.         
  24.         std::sort(data.begin(), data.end());
  25.         
  26.         size_t size = data.size();
  27.         if (size % 2 == 0) {
  28.             return (data[size/2 - 1] + data[size/2]) / 2.0;
  29.         } else {
  30.             return data[size/2];
  31.         }
  32.     }
  33.    
  34.     double variance() const {
  35.         if (data.size() < 2) return 0.0;
  36.         
  37.         double m = mean();
  38.         double sum = 0.0;
  39.         for (double value : data) {
  40.             sum += (value - m) * (value - m);
  41.         }
  42.         
  43.         return sum / (data.size() - 1); // 样本方差
  44.     }
  45.    
  46.     double standardDeviation() const {
  47.         return std::sqrt(variance());
  48.     }
  49.    
  50.     // 偏度和峰度
  51.     double skewness() const {
  52.         if (data.size() < 3) return 0.0;
  53.         
  54.         double m = mean();
  55.         double s = standardDeviation();
  56.         
  57.         if (s == 0.0) return 0.0;
  58.         
  59.         double sum = 0.0;
  60.         for (double value : data) {
  61.             double z = (value - m) / s;
  62.             sum += z * z * z;
  63.         }
  64.         
  65.         return sum / data.size();
  66.     }
  67.    
  68.     double kurtosis() const {
  69.         if (data.size() < 4) return 0.0;
  70.         
  71.         double m = mean();
  72.         double s = standardDeviation();
  73.         
  74.         if (s == 0.0) return 0.0;
  75.         
  76.         double sum = 0.0;
  77.         for (double value : data) {
  78.             double z = (value - m) / s;
  79.             sum += z * z * z * z;
  80.         }
  81.         
  82.         return sum / data.size() - 3.0; // 超出峰度
  83.     }
  84.    
  85.     // 百分位数
  86.     double percentile(double p) {
  87.         if (data.empty() || p < 0.0 || p > 100.0) return 0.0;
  88.         
  89.         std::sort(data.begin(), data.end());
  90.         
  91.         double n = data.size();
  92.         double pos = p * (n - 1) / 100.0;
  93.         int k = static_cast<int>(pos);
  94.         double d = pos - k;
  95.         
  96.         if (k + 1 < static_cast<int>(n)) {
  97.             return data[k] + d * (data[k + 1] - data[k]);
  98.         } else {
  99.             return data[k];
  100.         }
  101.     }
  102.    
  103.     // 直方图
  104.     std::vector<int> histogram(int bins) {
  105.         if (data.empty() || bins <= 0) return {};
  106.         
  107.         auto [minIt, maxIt] = std::minmax_element(data.begin(), data.end());
  108.         double minVal = *minIt;
  109.         double maxVal = *maxIt;
  110.         
  111.         if (minVal == maxVal) return std::vector<int>(bins, static_cast<int>(data.size()));
  112.         
  113.         double binWidth = (maxVal - minVal) / bins;
  114.         std::vector<int> hist(bins, 0);
  115.         
  116.         for (double value : data) {
  117.             int binIndex = static_cast<int>((value - minVal) / binWidth);
  118.             if (binIndex >= bins) binIndex = bins - 1; // 处理最大值
  119.             hist[binIndex]++;
  120.         }
  121.         
  122.         return hist;
  123.     }
  124.    
  125.     // 相关性
  126.     double correlation(const std::vector<double>& other) const {
  127.         if (data.size() != other.size() || data.empty()) return 0.0;
  128.         
  129.         double meanX = mean();
  130.         double meanY = std::accumulate(other.begin(), other.end(), 0.0) / other.size();
  131.         
  132.         double numerator = 0.0;
  133.         double sumSqX = 0.0;
  134.         double sumSqY = 0.0;
  135.         
  136.         for (size_t i = 0; i < data.size(); i++) {
  137.             double devX = data[i] - meanX;
  138.             double devY = other[i] - meanY;
  139.             
  140.             numerator += devX * devY;
  141.             sumSqX += devX * devX;
  142.             sumSqY += devY * devY;
  143.         }
  144.         
  145.         double denominator = std::sqrt(sumSqX * sumSqY);
  146.         if (denominator == 0.0) return 0.0;
  147.         
  148.         return numerator / denominator;
  149.     }
  150.    
  151.     // 生成统计报告
  152.     void generateReport() {
  153.         std::cout << std::fixed << std::setprecision(4);
  154.         std::cout << "科学数据统计分析报告" << std::endl;
  155.         std::cout << "======================================" << std::endl;
  156.         std::cout << "样本数量: " << data.size() << std::endl;
  157.         std::cout << "平均值: " << mean() << std::endl;
  158.         std::cout << "中位数: " << median() << std::endl;
  159.         std::cout << "方差: " << variance() << std::endl;
  160.         std::cout << "标准差: " << standardDeviation() << std::endl;
  161.         std::cout << "偏度: " << skewness() << std::endl;
  162.         std::cout << "峰度: " << kurtosis() << std::endl;
  163.         
  164.         std::cout << "\n百分位数:" << std::endl;
  165.         std::cout << "最小值: " << percentile(0) << std::endl;
  166.         std::cout << "25%: " << percentile(25) << std::endl;
  167.         std::cout << "50% (中位数): " << percentile(50) << std::endl;
  168.         std::cout << "75%: " << percentile(75) << std::endl;
  169.         std::cout << "最大值: " << percentile(100) << std::endl;
  170.         
  171.         // 直方图
  172.         int bins = 10;
  173.         auto hist = histogram(bins);
  174.         std::cout << "\n直方图 (" << bins << " 个区间):" << std::endl;
  175.         
  176.         auto [minIt, maxIt] = std::minmax_element(data.begin(), data.end());
  177.         double minVal = *minIt;
  178.         double maxVal = *maxIt;
  179.         double binWidth = (maxVal - minVal) / bins;
  180.         
  181.         int maxCount = *std::max_element(hist.begin(), hist.end());
  182.         int maxStars = 50;
  183.         
  184.         for (int i = 0; i < bins; i++) {
  185.             double lower = minVal + i * binWidth;
  186.             double upper = lower + binWidth;
  187.             
  188.             std::cout << "[" << std::fixed << std::setprecision(2) << lower
  189.                       << ", " << upper << "): ";
  190.             
  191.             int stars = (hist[i] * maxStars) / maxCount;
  192.             for (int j = 0; j < stars; j++) {
  193.                 std::cout << "*";
  194.             }
  195.             
  196.             std::cout << " (" << hist[i] << ")" << std::endl;
  197.         }
  198.         
  199.         std::cout << "======================================" << std::endl;
  200.     }
  201. };
  202. int main() {
  203.     // 生成测试数据 - 正态分布
  204.     const int size = 1000;
  205.     std::vector<double> data(size);
  206.    
  207.     std::random_device rd;
  208.     std::mt19937 gen(rd());
  209.     std::normal_distribution<> dist(100.0, 15.0);
  210.    
  211.     for (int i = 0; i < size; i++) {
  212.         data[i] = dist(gen);
  213.     }
  214.    
  215.     // 创建分析器并生成报告
  216.     ScientificDataAnalyzer analyzer(data);
  217.     analyzer.generateReport();
  218.    
  219.     // 测试相关性
  220.     std::vector<double> data2(size);
  221.     for (int i = 0; i < size; i++) {
  222.         // 创建与data有线性关系的数据
  223.         data2[i] = 2.0 * data[i] + 10.0 + (dist(gen) - 100.0) * 0.5;
  224.     }
  225.    
  226.     double corr = analyzer.correlation(data2);
  227.     std::cout << "\n两组数据的相关系数: " << corr << std::endl;
  228.    
  229.     return 0;
  230. }
复制代码

总结与展望

本文从基础语法到高级应用,全面介绍了如何在C++中精确统计并高效输出数字的个数。我们学习了:

1. 基础语法:基本数据类型、输入输出流和基本计数方法。
2. 中级应用:数组、字符串和文件中的数字统计。
3. 高级应用:使用STL容器和算法、多种数据类型的数字统计以及性能优化技巧。
4. 实际案例分析:数据分析、游戏开发和科学计算中的数字统计应用。

通过这些内容,读者应该能够掌握C++中数字统计的核心技能,并能够将其应用到实际项目中。

随着C++标准的不断发展,我们有理由相信未来会有更多强大的工具和库来支持数字统计和数据分析。例如,C++20引入的范围库(Ranges)和概念(Concepts)将进一步简化数据处理的代码。此外,随着并行计算和GPU编程的普及,我们也将看到更多高效的数字统计算法的出现。

无论你是初学者还是有经验的开发者,掌握数字统计这一核心技能都将对你的编程之路产生积极影响。希望本文能够帮助你更好地理解和应用C++中的数字统计技术。
「七転び八起き(ななころびやおき)」
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则