指针练习--人工智能之双色球预测系统

双色球是7个球组成,前6个球是一个颜色,后6个球是一个颜色,从文件中读取一段时间内的双色球中奖号码,统计每组号码前6个球出现的概率。

//----------------  ball.txt文件  ---------------
  8 11 17 23 32 33      10
  4  5  7 10 12 22      16
  3 13 15 18 21 33      16
  4  8  9 13 28 33       4 
  9 15 19 21 23 29      15
  9 11 15 22 24 26       3 
  1  5  7  9 10 20      16
  2 10 13 16 23 32       8
  1 7  12 14 18 25      10
  9 12 21 27 29 30       5 

代码

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <fstream>
#include <iomanip>

#define MAXBALL 33  // 有1-33个球号
#define BALL 7      // 双色球每组有7个球
using namespace std;

// 统计每个球出现的次数,pash:文件名,ball:存放统计结果的数组,len:ball数组的长度
bool statistics(const char* path, int* ball, int len)
{
    ifstream file;
    int result[BALL] = { 0 };
    if (!path)
    {
        cout << "path is null" << endl;
        return false;
    }
    file.open(path);
    if (file.fail())
    {
        cout << "打开输入文件出错" << endl;
        return false;
    }

    // 从文件读数据到数组中,双色球每组有7个球
    while (1)
    {
        int i = 0;
        for (i = 0; i < BALL; i++)
        {
            file >> result[i];
            // 判断是否是文件结束符
            if (file.eof())
            {
                break;
            }
            if (file.fail())
            {
                cout << "读取文件失败,原因:" << strerror(errno) << endl;
                break;
            }
        }

        // 记录正常结束
        if (i == 0)
        {
            break;
        }
        if (i < BALL - 1)
        {
            cout << "仅读到" << i + 1 << "个记录,预期读取" << BALL << "个" << endl;
            return false;
        }


        // 打印一下读入的数据,这里也打印了最后一个颜色的球
        for (int i = 0; i < BALL; i++)
        {
            cout << setw(3) << left << result[i];
        }
        cout << endl;

        // 对读入的数据进行统计,每组最后一个颜色的球不统计
        for (int i = 0; i < BALL - 1; i++)
        {
            int index = *(result + i) - 1;
            if (index >= 0 && index < len)
            {
                *(ball + index) += 1;
            }
        }
    }
    file.close();
    return true;
}

int main()
{
    int ball[MAXBALL] = { 0 };  // 用来统计1-MAXBALL号球每个球出现的次数 
    string filename;
    cout << "请输入文件名:";
    cin >> filename;

    if (statistics(filename.c_str(), ball, MAXBALL))
    {
        // 打印统计结果
        for (int i = 0; i < MAXBALL; i++)
        {
            cout << i + 1 << "出现的次数:" << ball[i] << endl;
        }
    }
    else
    {
        cerr << "统计出错" << endl;
    }

    return 0;
}

image
我们这里打印的时候把最后一个颜色的球也打印出来了,最后一列球出现次数不计入统计结果中

posted @ 2022-04-19 06:52  荒年、  阅读(665)  评论(0编辑  收藏  举报