获取数组的SUM(C ++)

时间:2014-03-05 13:54:42

标签: c++ arrays

我需要从数组中计算数字。

我写了一段代码,但我不知道我究竟需要编写什么才能得到数组中数字的总和。

如果你会推荐一些好的材料来学习这样的东西,我会很感激。

#include <iostream>
#include <iomanip>
#include <fstream>

using namespace std;

int n;
int array_1[20];
const char D[]= "Data.txt";
const char R[]="Rezults.txt";

void to_read ( int &n, int array_1[])
{
ifstream fd(D);
fd>>n;
for (int i=0; i<n; i++)
fd>>array_1[i];
fd.close();
}

int to_sum()
{
int m=0;
for (int i=0; i<n; i++)
m=m+array_1[i];
return m;
}

void to_print(int n, int mas_1[])
{
int sum=0;
ofstream fr(R);
fr<<n<<endl;
for (int i=0; i<n; i++)
fr<<array_1[i]<<" ";
fr<<endl;
sum=to_sum();
fr<<sum<<endl;
fr.close();

}
int main()
{
to_read(n, array_1);
to_sum();
to_print(n, array_1);


return 0;
}

1 个答案:

答案 0 :(得分:0)

我重写了你的代码,删除了全局变量,更改了格式以便于阅读,重命名一些变量以更好地解释它们是什么并添加函数原型。希望这会对你有所帮助。

仍有很多地方需要更改,但我希望尽可能保持与原始代码的接近。

如果您有任何问题,请随时提出。

#include <iostream>
#include <fstream>

using namespace std;

//functions prototypes (these will be moved to header file if you wanna use this code from another file)
void to_read(int &len, int * array, const char * name); //added name parameter to avoid glogal variables
void to_print(int len, int * array, const char * name);
int to_sum(int len, int * array);                       //added parameters to avoid global variables

int main()
{
    int lenght = 20;                //moved to here, try to avoid global variables
    int array_1[lenght];            //preconfigured size depend on variable
    const char D[] = "Data.txt";
    const char R[] = "Rezults.txt";

    to_read(lenght, array_1, D);
    //to_sum(lenght, array_1);     //not needed here, not storing/processing result
    to_print(lenght, array_1, R);

    return 0;
}

void to_read(int &len, int * array, const char *name)
{
    int lenght;

    ifstream fd(name);              //you should check if opening was successful

    fd >> lenght;                     //you should check if reading was successful
    if (lenght < len) len = lenght; //to prevent overflow of array, read max 20

    for (int i=0; i<len; i++){
        fd >> array[i];
    }

    fd.close();
}

int to_sum(int len, int * array)
{
    int sum=0;

    for (int i=0; i<len; i++){
        sum += array[i];            //changed sum = sum + value; to sum += value; its same but this is more often used
    }

    return sum;
}

void to_print(int len, int * array, const char *name)
{
    int sum = to_sum(len, array);
    ofstream fr(name);

    fr << len << endl;

    for (int i=0; i<len; i++){
        fr << array[i] << " ";
    }

    fr << endl;
    fr << sum << endl;

    fr.close();
}