每行添加整数并将其存储在数组中
Adding integers per line and storing it in array
我正在尝试使用动态分配的数组而不是向量创建一个迷你函数,因为我试图弄清楚它们是如何工作的。
所以基本上,用户输入他们想要的行数,然后,他们输入一组由空格分隔的整数/双精度。然后,我希望函数计算每行整数的总和,并将其分配到数组中。
例如:
3
1 2 3 4
3 2 2 1 //assume each line has the same # of integers (4)
1 4 4 1
然后,如果我实现了我的函数,那么总和将是 10、8、10。
到目前为止,我有这个:
int* total //is there a difference if I do int *total ??
int lines;
std::cout << "How many lines?;
std::cin >> lines;
total = new int[lines];
for (int i=0;i<lines;i++)
{
for (int j=0;j<4;j++)
{
total[i] = ? //i'm confused how you add up each line and then put it in the array, then go onto the next array..
}
}
如果有什么不合理的地方,请随时询问!谢谢!
您可能希望将total[i]
设置为在内部循环之前0
,然后使用operator+=
添加从std::cin
流中获得的任何内容。
// ...
total[i]=0;
for (int j=0;j<4;j++)
{
int temp;
cin >> temp;
total[i] += temp;
}
// ...
如果您首先分配了一个数组来存储值,然后将它们加在一起,可能会更容易理解。
首先,您需要分配一个数组数组来存储每行的数字。例如
const size_t COLS = 4;
size_t rows;
std::cout << "How many lines? ";
std::cin >> rows;
int **number = new int *[rows];
for ( size_t i = 0; i < rows; i++ )
{
number[i] = new int[COLS];
}
int *total = new int[rows];
// or int *total = new int[rows] {}; that do not use algorithm std::fill
std::fill( total, total + rows, 0 );
之后,您应该输入数字并填写每一行数字。
执行int* total
和int *total
之间实际上没有任何区别(无论如何在您的示例中)。就个人而言,我更喜欢第二个。
至于您的问题,您需要将总计设置为初始值(在这种情况下,将其设置为零),然后在从那里获得值后从那里添加cin
。
使用 cin
,既然你有空格,它将获得每个单独的数字(如您所知,我假设),但是您可能应该(我会)将该数字存储到另一个变量中,然后将该变量添加到该行的总数中。
我认为这一切都是有道理的。希望对您有所帮助。
恕我直言,您可以使用二维数组来做到这一点:
int** total;
// ...
total = new int*[lines];
for(int i = 0; i < lines; ++i)
{
total[i] = new int[4]; // using magic number is not good, but who cares?
for(int j = 0; j < 4; ++j)
{
int tmp;
std::cin>>tmp;
total[i][j] = tmp;
}
}
// do sth on total
for(int i = 0; i < lines; ++i)
delete[] total[i];
delete[] total;
相关文章:
- 使用无符号字符数组有效存储内存
- 如何在cpp.中使用协议缓冲区存储大缓冲区/数组(char/int)
- 在c++中获取两个大int,并将它们存储在数组中
- 使用 Xcode 将双精度存储在数组C++中
- 访问表示 2D 矩阵的 1D 存储数组
- 从输入文件读取整数,仅存储数组C 中的唯一整数
- 如何在队列中存储数组
- 按列主要顺序迭代行大量存储数组
- 如何使存储数组的二进制搜索稳定
- 将行中的字段从textfile中更改为存储数组,而不是重新编写文件
- 存储数组索引值C++
- 存储数组的地方,如果我在返回后声明它
- 缺少存储数组地址的内存
- 使用static在函数中存储数组各个组件的值
- 如何存储数组的每个相邻子数组的和
- 在c++中存储数组映射
- 存储数组的地址列表,以解析原始的非终止文本
- 用于存储数组的字符串
- c++存储数组下一个位置的地址
- 在 for 循环中创建和存储数组