[英]C++ Filling partially filled 2D array with Average
我正在嘗試在C ++中使用2D數組進行實驗,並且正在開發一個項目,該項目制作了一個4x4 2D數組,該數組可以容納許多學生成績,但部分通過文本文件填充。 4列中僅填充3個。 我想用每列前幾行的平均成績來填充最后一列。
問題是我不知道如何准確地填充最后一列。
這是我的代碼,用於計算平均值。
const int SIZE = 4;
const int ROWS = 4;
const int COLS = 4;
int total = 0;
for (int i = 0; i < ROWS; i++)
{
total = 0;
for (int j = 0; j < COLS - 1; j++)
{
total += studentGrades[i][j];
average = total / (COLS - 1);
studentGrades[0][3] = average;
studentGrades[1][3] = average;
studentGrades[2][3] = average;
studentGrades[3][3] = average;
}
}
好像我接近了,因為我得到了很好的結果,但是最后一列顯示的值不正確,而且我覺得有一種更有效的方法來填充最后一列,而不是手動插入每個索引。
您每次都將最后一次計算的平均值分配給所有行。 這意味着最后您將獲得所有4列中第4行的平均值。 還可以考慮將變量( studentGrades
和total
)更改為浮點類型,以提高准確性。
const int SIZE = 4;
const int ROWS = 4;
const int COLS = 4;
for (int i = 0; i < ROWS; i++)
{
int total = 0;
for (int j = 0; j < COLS - 1; j++)
total += studentGrades[i][j];
studentGrades[i][COLS - 1] = total / (COLS - 1);
}
您還可以使用標准庫:
#include <numeric>
// ...
constexpr int Rows = 4, Cols = 4, NGrades = Cols - 1;
for (int i = 0; i < Rows; i++)
studentGrades[i][NGrades] = std::accumulate(studentGrades[i], studentGrades[i] + NGrades, 0) / NGrades;
與我的第一個解決方案一樣,請考慮使用浮點類型。 要啟用浮點運算,請將std::accumulate
的0
更改為0.0
或0.0f
。
這是std::accumulate
的解釋。
邏輯是錯誤的。 您只能計算平均值並在合計其他各列之后填充最后一列,並且一次只能填充一行,而不是嘗試一起完成所有四行。 這是正確的循環
for (int i = 0; i < ROWS; i++)
{
total = 0;
for (int j = 0; j < COLS - 1; j++)
{
total += studentGrades[i][j];
}
average = total / (COLS - 1);
studentGrades[i][3] = average;
}
這只是在正確的順序和正確的時間做事的問題。
另外,您應注意Yksisarvinen指出的整數除法問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.