编程知识 cdmana.com

C language basic problem solving

In the comparison function ,for Loop not executed , In the output result, only s1<s2
Personal problems , I think it's for The judgment condition of cycle i<s1.len&&i<s2.len error , But I think there's no problem .
But what I'm afraid of is that I think I'm right , Ask for an answer .

#include<stdio.h>#include<string.h>#define TRUE 1#define FALSE 0#define MAXLEN 9typedef struct{    char ch[MAXLEN];    int len;}SString; // Find the length  int Howlong(SString s){    int i;    for(i=0;s.ch[i]!='\0';i++);    return i;}// establish s2int Creat(SString *s){    int i;    char c;    printf(" establish s2, Please enter the string :( With '$' end ):");    scanf("%c",&c);    i=0;    while(c!='$'){        scanf("%c",&c);        s->ch[i]=c;        i++;    }    s->ch[i]='\0';    s->len=Howlong(*s);    //printf("%d",s->len);    return TRUE;} // Compare void Compare(SString s1,SString s2){    int i;    for(i=0;i<s1.len&&i<s2.len;i++)        if(s1.ch[i]!=s2.ch[i]){            if(s1.ch[i]-s2.ch[i]>0){            printf("s1>s2\n");            return;            }            else if(s1.ch[i]-s2.ch[i]<0){            printf("s1<s2\n");            return;            }        }    if(s1.len-s2.len>0)printf("s1>s2");    else if(s1.len-s2.len<0)printf("s1<s2");    else printf("s1==s2");    return;} // Display function , Test use void Show(SString s){    int i;    for(i=0;s.ch[i]!='\0';i++){        putchar(s.ch[i]);    }    printf("\n");}int main(){    SString s1={
   
   
   
   "abcdefg"},s2;    printf("s1=%s The length of the string is %d\n",s1.ch,Howlong(s1));    Creat(&s2);    Compare(s1,s2);    Show(s1);}



Refer to the answer 1:
  1. You can set breakpoints through debugging , To judge for(i=0;i<s1.len&&i<s2.len;i++) Does the office run as you think ;
  2. Debugging found ,s2 adopt Creat function s2.len There is an assignment ,s1.len Then for 0
  3. The correct code is as follows
int main(){    SString s1={
   
   
   
   "abcdefg"},s2;    printf("s1=%s The length of the string is %d\n",s1.ch,Howlong(s1));    s1.len = Howlong(s1);    Creat(&s2);    Compare(s1,s2);    Show(s1);}



Refer to the answer 2:



Refer to the answer 3:

Learn to debug




Refer to the answer 4:

版权声明
本文为[CSDN Q & A]所创,转载请带上原文链接,感谢
https://cdmana.com/2021/10/20211023224522191c.html

Scroll to Top