C语言。虽然过了,但是有些地方不明白。求求大佬解答

P1957 口算练习题

windsmoke @ 2023-01-25 17:15:38

如果把第67行的getchar()==' '改成getchar()!='\n',就有些测试点显示错误,但是我觉得两个写法本质都是一样的,都是判断输入的是两个数据还是三个数据。求求大佬解答。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct f
{
    int a;
    int b;
    int c;
    int length;
    char ch;
}f;
void output(char x[50],char y[50],char z[50],int i,f s[50])
{
    int a,b,c;
    char temp[10];
    if (x[0]=='a')
    {
       sscanf(y,"%d",&a);
       sscanf(z,"%d",&b);
       c=a+b;
       sprintf(temp,"%d",c);
       s[i].a=a;
       s[i].b=b;
       s[i].c=c;
       s[i].length=strlen(y)+strlen(z)+2+strlen(temp);
       s[i].ch='+';
    }
    else if(x[0]=='b')
    {
      sscanf(y,"%d",&a);
       sscanf(z,"%d",&b);
       c=a-b;
       sprintf(temp,"%d",c);
       s[i].a=a;
       s[i].b=b;
       s[i].c=c;
       s[i].length=strlen(y)+strlen(z)+2+strlen(temp);
       s[i].ch='-';
    }
    else if(x[0]=='c')
    {
       sscanf(y,"%d",&a);
       sscanf(z,"%d",&b);
       c=a*b;
       sprintf(temp,"%d",c);
       s[i].a=a;
       s[i].b=b;
       s[i].c=c;
       s[i].length=strlen(y)+strlen(z)+2+strlen(temp);
       s[i].ch='*';
    }
}
 int main()
 {
     f s[50];
     int n;
     scanf("%d",&n);
     char x[50],y[50],z[50],tempx[50],tempy[50],tempz[50];

     for(int i=0;i<n;i++)
     {
         scanf("%s%s",tempx,tempy);

         if(getchar()==' ')
         {
             scanf("%s",tempz);
             strcpy(x,tempx);
             strcpy(y,tempy);
             strcpy(z,tempz);
         }
         else
         {
             strcpy(y,tempx);
             strcpy(z,tempy);
         }
         output(x,y,z,i,s);

     }
     for(int i=0;i<n;i++)
     {
         printf("%d%c%d=%d\n",s[i].a,s[i].ch,s[i].b,s[i].c);
         printf("%d\n",s[i].length);
     }
     return 0;
 }

by Coffins @ 2023-01-25 17:43:46

@windsmoke 空格是'\0'


by windsmoke @ 2023-01-26 05:21:41

@Coffins 感谢回复。另外,我知道我错哪里了,我将\r写成\n了。


|