我正在使用数组,函数和随机数进行项目。当我运行程序时,它会给出一个指向第44行的错误。查看代码,我无法弄清楚问题是什么 错误说:int [i]不能在第44行转换为int。
知道出了什么问题吗? 顺便问一下,我可以用数字格式化吗?
// Debugging: grades.cpp
#include <iostream>
#include <iomanip>
#include <ctime>
using namespace std;
const int NUM_GRADES = 10;
const int NUM_SUDENTS = 3;
int findHighest( int * );
int findLowest( int * );
void printDatabase( const int [][NUM_GRADES], const char [][ 20 ] );
int main()
{
int student1[ NUM_GRADES ] = { 0 };
int student2[ NUM_GRADES ] = { 76, 89, 81, 42, 66, 93, 104,
91, 71, 85 };
int student3[ NUM_GRADES ] = { 65, 69, 91, 89, 82, 93, 72,
76, 79, 99 };
char names[ NUM_SUDENTS ][ 20 ] = { "Bob", "John", "Joe" };
int database[ NUM_SUDENTS ][ NUM_GRADES ];
int i = 0;
srand( time( 0 ) );
// initialize student1
for ( i = 0; i < NUM_GRADES; i++ )
student1[ NUM_GRADES ] = rand() % 50 + 50;
// initialize database
for ( i = 1; i < NUM_GRADES; i++ ) {
database[ 0 ][ i ] = student1[ i ];
database[ 1 ][ i ] = student2[ i ];
database[ 2 ][ i ] = student3[ i ];
} // end for
printDatabase( database, names );
for ( i = 0; i < NUM_SUDENTS; i++ ) {
cout << names[ i ] << "'s highest grade is: "
<< findHighest(database[i]) << endl // This is line 44 in my program
<< names[ i ] << "'s lowest grade is: "
<< findLowest( database[ i ] ) << endl;
} // end for
} // end main
// determine largest grade
int findHighest( int a[] )
{
int highest = a[ 0 ];
for ( int i = 1; i <= NUM_GRADES; i++ )
if ( a[ i ] > highest )
highest = a[ i ];
return highest;
} // end function findHighest
// determine lowest grade
int findLowest( int a[] )
{
int lowest = a[ 0 ];
for ( int i = 1; i < NUM_GRADES; i++ )
if ( a[ i ] < lowest )
lowest = a[ i ];
return lowest;
} // end lowestGrade
// output data
void printDatabase( int a[][ NUM_GRADES ], char names[][ 20 ] )
{
cout << "Here is the grade database\n\n"
<< setw( 10 ) << "Name";
for ( int n = 1; n <= NUM_GRADES; n++ )
cout << setw( 4 ) << n;
cout << endl;
for ( int i = 0; i < NUM_SUDENTS; i++ ) {
cout << setw( 10 ) << names[ i ];
for ( int j = 0; j < NUM_GRADES; j++ )
cout << setw( 4 ) << a[ i, j ];
cout << endl;
} // end for
cout << endl;
} // end printDatabase
答案 0 :(得分:0)
所以在查看之后我发现了一个编译错误。 &#34; printDatabase&#34;定义和声明不匹配。声明声明函数为const参数,但定义没有。
然而,一旦修复,运行时就会出现错误。问题在这里
for ( i = 0; i < NUM_GRADES; i++ )
student1[ NUM_GRADES ] = rand() % 50 + 50;
student1是NUM_GRADES的索引,这是student1数组的长度。但是,由于数组索引从0开始,最后一个索引将是NUM_GRADES - 1.因此,在这里写出超出数组的范围。虽然我相信查看代码所追求的行为是用i
索引for ( i = 0; i < NUM_GRADES; i++ )
student1[ i] = rand() % 50 + 50;