zoukankan      html  css  js  c++  java
  • 数组求和

    第一版本程序Prog1
    + 给定一个数组,实现数组元素求和;具体要求:实现对一维数组(a[100])的所有元素相加运算。
    + 数据准备:a)数组长度:100;b)数组数据来源:实验数据A列:1~100,CSV 格式则填充 前100个数据.

    凭个人感觉c++应该是读取不了excel的,所以把a列数据全部复制到txt文件里了。(汗)

    数据只有一列肯定不会读取错误的。。多列是否对程序有影响不得而知了。

    第一个程序主要是i/o流读取文件,然后求和

    #include<iostream>
    #include<fstream>
    using namespace std;
    
    int main()
    {
        int sum = 0, a[100];
        ifstream in("e:\data.txt");
        if (!in){ cout << "无法打开文件!"; }
        for (int i = 0; in >> a[i], i < 100; i++)
            sum += a[i];
        cout << sum;
        in.close();
        return 0;
    }

    程序结果如下

    第二版本程序Prog2
    + 改写成一个函数(函数名称为ArraySum),能实现任意长度数组所有元素求和;
    + 数据准备:a)数组长度:任意; b)数组数据来源:实验数据A列

    在程序1上稍加改动即可,加一个函数功能,申请动态数组

    #include<iostream>
    #include<fstream>
    using namespace std;
    int ArraySum(int n ,int t,int b)
    {
        int  *a = new int[n];
        int sum = 0;
        ifstream in("e:\data.txt");
        if (!in){ cout << "无法打开文件!"; }
        for (int i = 0; in >> a[i], i < n; i++)
            sum += a[i];
        in.close();
        return sum;
    
    }
    int main()
    {
        int n;
        cout << "输入数组长度";
        cin >> n;
        cout << "数组总和为";
        cout << ArraySum(n);
    
    
        return 0;
    }

    运行结果

    第三版本程序Prog3
    + 将Prog2改写成能从文件中读取数据,实现任意长度数组,指定范围内元素相加。
    + 数据准备:a)数组长度:任意; b)数组数据来源:从文件中读取(A列). c)指定范围: (bottom, top)

    依旧在上个函数上稍加改动 增加了对于数据范围的筛选,给出数据上下界(一开始把上下界弄反了,结果永远结果不对)

    #include<iostream>
    #include<fstream>
    using namespace std;
    int ArraySum(int n ,int top,int bottom)
    {
        int  *a = new int[n];
        int sum = 0;
        ifstream in("e:\data.txt");
        if (!in){ cout << "无法打开文件!"; }
        for (int i = 0; in >> a[i], i < n; i++)
        {
            if (a[i] <= top&&a[i] >= bottom)
                sum += a[i];
        }
        in.close();
        return sum;
    
    }
    int main()
    {
        int n,top,bottom;
        cout << "输入数组长度";
            cin >> n;
        cout << "输入数据上界";
            cin >> top;
        cout << "输入数据下届";
            cin >> bottom;
    
        cout << "数组总和为";
        cout << ArraySum(n,top,bottom);
    
        return 0;
    }

    程序结果

    差点忘了链接https://github.com/sunhongyi1996/repository

    总结一下

    函数这部分写的比较简单,手动修改了excel数据可能减少了不少难度

    还有c++ 的i/o这部分学的太糟糕了,四处百度看书,请教同学终于知道怎么读取文件数据了。

  • 相关阅读:
    高并发的一些处理意见
    TP5单元测试
    你真的会玩SQL吗?和平大使 内连接、外连接
    微信公众号第三方平台开发概况
    MVC的基类
    Android TextView中显示图片
    Android之assets资源
    通用分页存储过程
    到处都是坑的微信支付V3之 微信支付回调页面
    微信公众平台无高级接口账号获取用户基本信息
  • 原文地址:https://www.cnblogs.com/sunhongyi/p/5256347.html
Copyright © 2011-2022 走看看