我在教自己C++並從教科書中解決問題。到目前爲止,我已經介紹了諸如數據類型,聲明,顯示,賦值,交互式輸入,選擇(if-else)和重複(for/while循環...),函數和數組等基本知識。我還沒有對指針什麼,但我知道他們是什麼...從C++函數返回數組
我碰到這個問題就來了:
到真僞檢驗的答案如下:TTFF T.給定二維答案數組,其中每行對應於在一個測試中提供的答案,編寫一個接受二維數組和測試次數作爲參數的函數,並返回一個包含每個測試成績的一維數組。 (每題5分,從而最大可能的等級爲25)具有以下數據測試你的函數:
我的理解是,C++函數不能返回數組 - 至少,這是我在這個論壇上的其他帖子上閱讀的內容。它是否正確?如果是這樣,他們如何期待你做這個問題,因爲我還沒有指出。我認爲可能的唯一的另一種方式是通過引用來傳遞數組......但問題詞幹只說有2個參數給函數,所以我想也許這種方法被排除了。該方法將需要第三個參數,它是您修改的數組,因此它會隱式返回。
我有一些代碼,但它不正確(只有我的calcgrade功能需要工作),我不知道如何前進。請有人請指教?謝謝!!
#include<iostream>
// Globals
const int NROW = 6, NCOL = 5;
bool answers[NCOL] = {1, 1, 0, 0, 1};
bool tests[][NCOL] = {1, 0, 1, 1, 1,
1, 1, 1, 1, 1,
1, 1, 0, 0, 1,
0, 1, 0, 0, 0,
0, 0, 0, 0, 0,
1, 1, 0, 1, 0};
int grade[NROW] = {0};
// Function Proto-Types
void display1(bool []);
void display2(bool [][NCOL]);
int calcgrade(bool [][NCOL], int NROW);
int main()
{
calcgrade(tests, NROW);
display2(tests);
return 0;
}
// Prints a 1D array
void display1(bool answers[])
{
// Display array of NCOL
for(int i = 0; i < NCOL; i++)
std::cout << std::boolalpha << answers[i] << std::endl;
return;
}
// Print 2d Array
void display2(bool answers[][NCOL])
{
// Display matrix: 6x5
for(int i = 0; i < NROW; i++)
{
for(int j= 0; j < NCOL; j++)
{
std::cout << std::boolalpha << answers[i][j] << std::endl;
}
std::cout << std::endl;
}
return;
}
int calcgrade(bool tests[][NCOL], int NROW)
{
for(int i = 0; i < NROW; i++)
{
for(int j = 0; j < NROW; j++)
{
if(tests[i][j]==answers[j])
grade[i] += 5;
}
printf("grade[%i] = %i", i, grade[i]);
}
return grade;
}
正確的答案是返回一個'VECTOR'。如果你的教科書正在教你關於數組而不是'vector's,作者不應該被允許再次寫。 –
我的書甚至不會談論矢量......( – user1527227
)如果你有一本C++書籍,其中沒有章節涵蓋C++標準庫,並且在'std :: vector <>'的情況下,可以說這個庫在所有現代C++程序中使用最多的類型,你需要另外一本書(並且作者需要不同的職業) – WhozCraig