给定程序 c12-2-7.c 的中的 cmpstr 函数实现 2 个字符串相比较。当 s1=s2 时,函数返回 值为 0,如果 sl≠s2,则返回它们二者第一个不相同字符的 ASCII 码差值(如“BOY”与“BAD” 的第二个字母不相同,'O'与'A'的 ASCII 之差为 79—65=14)。下列 cmpstr 函数中有 2 个错 误,请改正程序中的错误。程序正确运行输出结果如图 12-5 所示。 图 12-5 程序 c12-2-7.c 的运行结果示例 /* c12-2-7.c */ #include<stdio.h> int cmpstr(char *s1,char*s2) { char *p1,*p2; p1=s1; p2=s2; while(*p1!=0 || *p2!=0) { if(*p1==*p2) { p1++; p2++; } else break; } return p1-p2; } int main() { char s1[80],s2[80]; int c; printf("please input string s1:"); gets(s1); printf("string s1 is:%s\n",s1); printf("please input string s2:"); gets(s2); printf("string s2 is:%s\n",s2); c=cmpstr(s1,s2); if(c>0) printf("s1>s2\n"); else if(c<0) printf("s1<s2\n"); else printf("s1==s2\n"); return 0; }
时间: 2024-03-09 12:49:27 浏览: 22
修改后的程序如下:
```
#include <stdio.h>
int cmpstr(char *s1, char *s2) {
char *p1, *p2;
p1 = s1;
p2 = s2;
while (*p1 != '\0' && *p2 != '\0') { // 修改1:改为逻辑与
if (*p1 == *p2) {
p1++;
p2++;
} else { // 修改2:添加 else 语句
return *p1 - *p2;
}
}
return *p1 - *p2;
}
int main() {
char s1[80], s2[80];
int c;
printf("please input string s1: ");
gets(s1);
printf("string s1 is: %s\n", s1);
printf("please input string s2: ");
gets(s2);
printf("string s2 is: %s\n", s2);
c = cmpstr(s1, s2);
if (c > 0) {
printf("s1 > s2\n");
} else if (c < 0) {
printf("s1 < s2\n");
} else {
printf("s1 == s2\n");
}
return 0;
}
```
主要的修改有两处:
1. 将 `while(*p1!=0 || *p2!=0)` 修改为 `while(*p1!=0 && *p2!=0)`,因为两个字符串必须同时遍历完才能比较大小。
2. 在 `if (*p1 == *p2)` 的后面添加 `else` 语句,因为当两个字符不相等时,应该立即返回它们的 ASCII 码差值,而不是继续比较下去。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)