我正在尝试使用指针创建一个数组循环。例如,
2 3 1 2
3 1 2 2
4 3 2 2
行数未定,因此我们不知道将有多少行整数。我将这些整数数据存储到一个名为“score”的指针变量中。所以,如果我想访问它们,
scores[0][0] = 2
scores[0][2] = 1
我正在尝试创建一个for循环,它会将每个整数除以2,然后加上总和。所以,如果我实现了一个函数,我希望它的值是
4 // (2/2) + (3/2) + (1/2) + (2/2) = 4
4
5.5
这是我到目前为止所做的,但它没有用。
int *total;
int lines;
total = new int[lines]; //lines: how many lines there are (assume it is passed through a parameter)
for (int i=0;i<lines;i++)
{
for (int j=0;j<howmany;j++) //howmany is how many integers there are per line (assume it is passed again)
{
total[i] = scores[i][j] //not sure how to divide it then accumulate the sum per line and store it
假设“得分”已经包含整数数据,我们在其他地方提取整数数据,因此用户不输入任何内容。 我想通过总[0],总[1]等来访问计算的总和。
答案 0 :(得分:2)
用于整数除法
// (2/2) + (3/2) + (1/2) + (2/2) = 4
this will give 3, not 4
这将给你4
// (2 + 3 + 1 + 2 ) / 2 = 4
您期望5.5
等价值,因此您应该将结果定义为float
或double
float *result;
int lines = 3; // need to initialize local variable before new. for this case, we set the lines to 3.
int total;
result = new float[lines]; //lines: how many lines there are (assume it is passed through a parameter)
for (int i=0;i<lines;i++)
{
total = 0;
for (int j=0;j<howmany;j++) //howmany is how many integers there are per line (assume it is passed again)
{
total += scores[i][j];
}
result[i] = (float)total/2;
}