腾讯云 ubuntu:C语言,找错误(逻辑错误)

来源:百度文库 编辑:高校问答 时间:2024/05/08 06:39:15
#include <stdio.h>
int EnterScore ( int P_array[] ) ;
void find ( int P_array[] , int count ) ;
int main ( void )
{
int array[80] , count ;
EnterScore ( array ) ;
find ( array , count ) ;
return 0 ;
}
int EnterScore ( int P_array[] )
{
int count = 0 ;
do
{
printf ( "Enter students' score : \n" ) ;
scanf ( "%d" , P_array[count] ) ;
count++ ;
}
while ( P_array[ count - 1 ] != -1 ) ;
return count ;
}
void find ( int P_array[] , int count )
{
int x , y , i ;
printf ( "Enter the students' score's scope : \n" ) ;
scanf ( "%d,%d" , &x , &y ) ;
for ( i = 0 ; i < count ; i++ )
{
if ( P_array[i] >= x && P_array[i] <= y )
{
printf ( "The score is %d.\n" , P_array[i] ) ;
}
}
}

1.在函数:int EnterScore ( int P_array[] )定义中:
DO循环中:scanf ( "%d" , P_array[count] ) ; 语句
有错误,应为:scanf ( "%d" , &P_array[count] ) ;
2.在函数:int EnterScore ( int P_array[] )定义中:
DO循环容易造成数组下标越界。如果你在前80个成绩输入
中都没有输入-1的话就会访问到P_array[80]这个元素,
但是实际上该数组最大的元素为:P_array[79],这会
破坏内存,甚至引起操作系统的崩溃。
3.在函数:void find ( int P_array[] , int count )
定义中,如果传入的数据:count大于数组的总元素个
数并且没有满足for语句中的if条件的数据时,
也会发生第2点的错误。

我不知道此程序的目的。你是不是想重复输入学生成绩的范围?那可以这样。
scanf ( "%d,%d" , &x , &y ) ;
for ( i = 0 ; i < count ; i++ )
{
if ( P_array[i] >= x && P_array[i] <= y )
printf ( "The score is %d.\n" , P_array[i] ) ;
else
scanf ( "%d,%d" , &x , &y ) ;
}

EnterScore ( array ) ;
改成
count = EnterScore( array );
原因自己想