我正在自学 C++,并根据教科书做一道题。到目前为止,我已经介绍了一些基础知识,例如数据类型、声明、显示、赋值、交互式输入、选择(if-else)和重复(for/while 循环...)、函数和数组。我没有对指针做过任何事情,但我知道它们是什么......
我遇到了这个问题:
The answers to a true-false test are as follows: T T F F T. Given a two-dimensional answer array, in which each row corresponds to the answers provided on one test, write a function that accepts the two-dimensional array and number of tests as parameters and returns a one-dimensional array containing the grades for each test. (Each question is worth 5 points so that the maximum possible grade is 25.) Test your function with the following data:
我的理解是 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;
}
最佳答案
尝试使用std::vector .
vector 是表示可以更改大小的数组的序列容器。
你可以这样做:
vector<bool> function()
{
vector<bool> vec;
vec.push_back(true);
vec.push_back(false);
vec.push_back(true);
return vec;
}
关于c++ - 从 C++ 函数返回数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19885443/