|
发表于 2019-10-20 15:58:35
|
显示全部楼层
本帖最后由 jackz007 于 2019-10-20 16:15 编辑
这句代码有错:
scanf("%d",&a,&b);
在 star1[0] == star2[0] 的情况下,这个代码无疑会是死循环,必须把 n = 0 放循环外头!
do {
n = 0 ;
d = star1[n] - star2[n] ;
n +=1 ;
} while(d = 0 && n! = a - 1) ;
此外,如果 a、b 不一样大,而且,a > b,则把 a 用作 star2 的下标,会导致下标超界。
所以,代码应该这么修改:
- #include<stdio.h>
- int main() //模仿strncmp函数
- {
- int a , b , e , n , d ;
- char c ;
- scanf("%d%d" , & a , & b) ;
- e = (a > b) ? a : b ;
- char star1[e] ;
- char star2[e] ;
- for(n = 0 ; n < e ; n ++) star1[n] = 0 , star2[n] = 0 ;
- printf("请输入:") ;
- fflush(stdin) ;
- for(n = 0 ; n < a - 1 && (c = getchar()) != '\n' ; n ++) star1[n] = c ;
- star1[n - 1] ='\0' ;
- a = n ;
- printf("请输入:") ;
- fflush(stdin) ;
- for(n = 0 ; n < b - 1 && (c = getchar()) != '\n' ; n ++) star2[n] = c ;
- star2[n - 1] = '\0' ;
- b = n ;
- e = (a > b) ? a : b ;
- for(n = 0 ; n < e && ! (d = star1[n] - star2[n]) ; n ++) ;
- printf("%d\n" , d) ;
- }
复制代码
|
|