配列から数値を計算する必要があります。
私はコードを書いていますが、配列内の数値の合計を取得できるように、どれだけ正確に書く必要があるのかわかりません。
そのようなことを学ぶために良い資料をお勧めしていただければ幸いです。
#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;
}
コードを書き直し、グローバル変数を削除し、読みやすくするためにフォーマットを変更し、いくつかの変数の名前を変更して、それらが何であるかをより説明し、関数プロトタイプを追加しました。これが少しお役に立てば幸いです。
変更が必要な箇所はまだたくさんありますが、できるだけ元のコードに近づけたいと思います。
ご不明な点がございましたら、お気軽にお問い合わせください。
#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();
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加