#include <iostream>
using namespace std;
int grade(char [][5], int);
int main()
{
int tests, i,j;
cout << "How many tests?"; cin >> tests;
char answers[tests][5];
cout << "What were the answers for all the tests (T/F)?";
for (i=0;i<tests;i++)
for (j=0;j<5;j++) cin >> answers[i][j];;
int g[tests] = {grade(answers, tests)};
for (i=1;i<=tests;i++)
{
cout << "\n Test " << i << ": ";
cout << g[i-1] << " out of 25";
}
cout << endl;
return 0;
}
int grade(char ans[][5], int test)
{
int k, l;
int gr[test]={0};
char sheet[5] = {'T', 'T', 'F', 'F', 'T'}; cout << sheet[1];
for (k=0;k<test;k++)
for (l=0;l<5;l++)
if (ans[k][l]==sheet[l]) gr[k]+= 5;;;
return *gr;
}
我无法弄清楚为什么我的程序如此不一致。如果我输入T T F F T进行第一次测试,一切都很好,但如果我有任何错误答案&#34;对于第一次测试,我的g数组的值似乎总是为0。
有什么想法吗?谢谢!
答案 0 :(得分:0)
这是问题所在。函数的返回值返回单个数字,然后将该单个数字分配给数组的所有值。所以,无论第一个考试成绩如何,所有成绩都是相同的。
数组之后的{}设置数组的初始值,并且只有一个值使得该值被赋值给数组的所有部分。
我的编译器不喜欢int g[tests]
的语法,因为它期望tests
是常量,所以我必须转换那些动态数组大小声明。下面的代码在Visual Studio 2017上按预期工作。试试这个。
#include <iostream>
using namespace std;
int* grade(char** ans, int test);
int main()
{
int tests, i, j;
cout << "How many tests?"; cin >> tests;
char** answers = new char*[tests];
for (int i=0;i<tests;i++)
answers[i] = new char[5];
cout << "What were the answers for all the tests (T/F)?";
for (i = 0; i<tests; i++)
for (j = 0; j<5; j++) cin >> answers[i][j];
int* g = grade(answers, tests);
for (i = 1; i <= tests; i++)
{
cout << "\n Test " << i << ": ";
cout << g[i - 1] << " out of 25";
}
cout << endl;
for (int i = 0; i < tests; i++)
delete[] answers[i];
delete[] answers;
delete[] g;
system("pause");
return 0;
}
int* grade(char** ans, int test)
{
int k, l;
int* gr = new int [test] {0};
char sheet[5] = { 'T', 'T', 'F', 'F', 'T' };
cout << sheet[1];
for (k = 0; k<test; k++)
for (l = 0; l<5; l++)
if (ans[k][l] == sheet[l]) gr[k] += 5;;;
return gr;
}