数组求和

第一版本程序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

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值