一、问题
输入字符串1和字符串2,如果两个字符串相同,输出0;如果字符串1大于字符串2,输出1;如果字符串1小于字符串2,输出-1。比如:
输入:
hello
world
则输出:-1
输入:
world
hello
则输出1
输入:
hello
hello
则输出:0
二、代码
#include <stdio.h>
#include <string.h>
int main(){
char a[256];//最好定义长度,要不然报错
char b[256];
scanf("%s%s",&a,&b);
if(strcmp(a,b)==0){//注意strcmp函数用法
printf("%d",0);//数字是0时,用printf(0);输出的就是没东西,必须这样哟
}
else if(strcmp(a,b)>0){
printf("%d",1);
}
else{
printf("%d",-1);
}
return 0;
}
三、tips
1.又遇见strcmp函数
strcmp(a,b):
1.a的ascll码大于b:返回值大于0
2.a的ascll码等于b:返回值等于0
3.a的ascll码小于b:返回值小于0
2.printf不可直接
printf(0)//这样输出不了0,不会报错,运行页面是啥都不输出
printf(5)//这样就会报错
该代码示例展示了如何在C语言中使用strcmp函数比较两个字符串。根据strcmp的返回值,程序会输出0(表示两个字符串相同)、1(字符串1大于字符串2)或-1(字符串1小于字符串2)。注意,printf函数输出0时需用引号括起来,否则可能无显示。
3535

被折叠的 条评论
为什么被折叠?



