数组求和

第一版本程序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这部分学的太糟糕了,四处百度看书,请教同学终于知道怎么读取文件数据了。
原文链接: https://www.cnblogs.com/sunhongyi/p/5256347.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/229914

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月13日 下午2:28
下一篇 2023年2月13日 下午2:29

相关推荐