我正在做一个使用数组、函数和随机数的项目。当我运行程序时,它给出了指向第 44 行的错误。查看代码,我无法弄清楚问题是什么。
错误提示:第 44 行无法将 int [i] 转换为 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
最佳答案
所以看了之后发现编译错误。 “printDatabase”定义和声明不匹配。声明声明函数采用 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;
关于c++ - 数组、函数和随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26643575/