C++ 每行添加整数并将其存储在数组中
我试图使用动态分配的数组而不是向量来创建一个小函数,因为我试图弄清楚它们是如何工作的 基本上,用户输入他们想要的行数,然后输入一组由空格分隔的整数/双精度数。然后,我想让函数计算每一行中整数的总和,将其分配到数组中 例如:C++ 每行添加整数并将其存储在数组中,c++,arrays,C++,Arrays,我试图使用动态分配的数组而不是向量来创建一个小函数,因为我试图弄清楚它们是如何工作的 基本上,用户输入他们想要的行数,然后输入一组由空格分隔的整数/双精度数。然后,我想让函数计算每一行中整数的总和,将其分配到数组中 例如: 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 d
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..
}
}
int*total//如果我做int*total有什么区别吗??
内线;
std::cout您可能希望将total[i]
设置为0
,然后使用操作符+=
添加从std::cin
流中获得的任何内容
// ...
total[i]=0;
for (int j=0;j<4;j++)
{
int temp;
cin >> temp;
total[i] += temp;
}
// ...
/。。。
总数[i]=0;
对于(int j=0;j>temp;
总[i]+=温度;
}
// ...
如果您首先分配一个数组来存储值,然后将它们添加到一起,则可能会更容易理解。如何使用二维数组:
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;
int**total;
// ...
总计=新整数*[行];
对于(int i=0;i>tmp;
总[i][j]=tmp;
}
}
//完全做某事
对于(int i=0;i
首先,您需要分配一个数组来存储每行的编号。例如
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 );
const size\u t COLS=4;
行大小;
std::cout>行;
整数**编号=新整数*[行];
对于(大小i=0;i
在这之后,你应该输入数字并填写每行数字。执行int*total
和int*total
(无论如何,在你的例子中)之间真的没有任何区别。我个人更喜欢第二个
至于您的问题,您需要将总数设置为初始值(在本例中,您需要将其设置为零),然后从cin
获取值后,再将其添加到该值上
使用cin
,由于您有空格,它将获得每个单独的数字(如您所知,我假设),但是您可能应该(我会)将该数字存储到另一个变量中,然后将该变量添加到该行的总数中
我认为这一切都有道理。希望能有所帮助。int*total
和int*total
是一样的。这没有任何“累加”的成分。@BenVoigt它应该在//我忽略的关于total
的部分。