问题描述
我正在创建一个程序来生成给定行数的随机数据,每行有 10 个从 -50 到 50 的随机整数值。最后一列是行值的总和。
我无法将随机数据写入文本文件。最后一列似乎是我运行时唯一的问题。
我是新手,所以请耐心等待。
到目前为止,这是我的程序:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
using namespace std;
//function prototype
void writeData(int,int);
int main() {
int ROWS;
const int COLS = 10;
cout << "Enter number of rows (10-25): ";
cin >> ROWS;
writeData(ROWS,COLS);
return 0;
}//end main
void writeData(int ROWS,const int COLS) {
//Create an array with column count.
int arr[ROWS][COLS];
//Seed the random number generator.
srand((unsigned)time(0));
//Create and open a file.
ofstream outputFile;
outputFile.open("myfile.txt");
//Generate a random number (between 10 and 25) of rows of random data.
//Write random data to file.
outputFile << "[" << ROWS << "," << COLS+1 << "]\n";
int sum = 0;
for(int i=0; i<ROWS; i++) {
for(int j=0; j<COLS; j++) {
arr[i][j] = (rand()%50)+(-50); //each row has 10 random integer values between -50 and 50
outputFile << ((int) arr[i][j]) << "\t";
sum += arr[i][j]; //sum row values
}
outputFile << arr[i][COLS] << sum << endl; //store row sum in last column in the row
sum = 0; //reset sum to 0
}
//Close the file.
outputFile.close();
//Confirm the data is written to file.
cout << "The data was saved to the file.\n";
}//end writeData
我得到这个输出:
[10,11]
-5 -7 -28 -48 -12 -2 -29 -28 -40 -18 0-217
-49 -11 -15 -20 -34 -40 -25 -46 -41 -42 1430822061-323
-3 -13 -27 -24 -13 -29 -44 -25 -43 -2 764375682-223
-43 -37 -32 -40 -26 -29 -30 -32 -22 -24 0-315
-31 -12 -2 -12 -38 -15 -27 -36 -24 -21 71091072-218
-11 -49 -48 -47 -10 -44 -32 -22 -31 -7 -343595632-301
-32 -17 -28 -34 -48 -46 -29 -9 -17 -13 0-273
-22 -46 -25 -3 -34 -14 -2 -32 -7 -22 400-207
-5 -13 -13 -14 -17 -47 -28 -19 -5 -36 10-197
-3 -1 -27 -4 -30 -43 -47 -20 -13 -16 -343595600-204
经过反复试验,我已经走到了这一步。现在,我被困住了。一些指导将不胜感激。
解决方法
关于您的计划有几点:
-
如果要在 [-50,+50] 中创建数字,请将
(rand()%50)+(-50)
更改为rand()*100-50
-
如果您不将
int arr[ROWS][COLS];
重用于任何东西:只需将其删除。 -
在正确的位置(循环内)声明
int sum=0;
-
不要将
arr[i][COLS]
(这也是一个越界错误,因为您超出了arr
的大小)到您的 outputFile 中。
所以正确的函数应该是:
void writeData(int ROWS,const int COLS) {
//Seed the random number generator.
srand((unsigned)time(0));
ofstream outputFile;
outputFile.open("myfile.txt");
outputFile << "[" << ROWS << "," << COLS+1 << "]\n";
for(int i=0; i<ROWS; i++) {
int sum = 0;
for(int j=0; j<COLS; j++) {
int const value = rand()*100-50;
outputFile << value << "\t";
sum += value;
}
outputFile << sum << endl; //store row sum in last column in the row
}
outputFile.close();
}//end writeData