求大神告知这串代码如何修改,谢谢啦(C语言初学者

P1957 口算练习题

Aiaoming @ 2024-12-19 13:47:23

#include<stdio.h>
#include<string.h>
int calculate(int a,int b,char op)
{
    switch (op)
    {
        case'a':
        return a+b;
        case'b':
        return a-b;
        case'c':
        return a*b;
        default:
        return 0;
    }
}
int main()
{
  int n;
  scanf("%d",&n);
  char op;
  int num1,num2;
  for(int i=0;i<n;i++)
  {

      scanf("%c %d %d",&op,&num1,&num2);
      int result=calculate(num1,num2,op);
      char equation[100];
      sprintf(equation,"%d%c%d=%d",num1,op,num2,result);
      printf("%s\n",result);
      printf("%d\n",(int)strlen(equation));
  }
  return 0;

}    

by EXR_FAL @ 2024-12-19 14:41:53

@Aiaoming
三个问题:

  1. 读入不能直接scanf()不然又读字符又读整数scanf会炸掉scanf(),这样写:
    char line[100];
    fgets(line,sizeof(line),stdin);
    sscanf(line,"%c %d %d",&op,&num1,&num2);

    2.op是读的'a' 'b' 'c'但题目要的是'+' '-' '*',所以加一个函数trans()转换:

    char trans(char c){
    switch (c)
    {
        case'a':
        return '+';
        case'b':
        return '-';
        case'c':
        return '*';
        default:
        return 0;
    }
    } 

    3.printf("%s\n",result);是认真的吗,result是个整数。。。 改成printf("%s\n",equation);
    完整代码:

    
    #include<stdio.h>
    #include<string.h>
    int calculate(int a,int b,char op)
    {
    switch (op)
    {
        case'a':
        return a+b;
        case'b':
        return a-b;
        case'c':
        return a*b;
        default:
        return 0;
    }
    }
    char trans(char c){
    switch (c)
    {
        case'a':
        return '+';
        case'b':
        return '-';
        case'c':
        return '*';
        default:
        return 0;
    }
    }
    int main()
    {
    int n;
    scanf("%d",&n);getchar();
    char op;
    int num1,num2;
    for(int i=0;i<n;i++)
    {
      char line[100];
      fgets(line,sizeof(line),stdin);
      sscanf(line,"%c %d %d",&op,&num1,&num2);
      int result=calculate(num1,num2,op);
      char equation[100];
      sprintf(equation,"%d%c%d=%d",num1,trans(op),num2,result);
      printf("%s\n",equation);
      printf("%d\n",strlen(equation));
    }
    return 0;

}


by Aiaoming @ 2024-12-19 20:29:35

@zhexueder妈呀,太强了大神,谢谢谢~~


|