C language basic questions

1. Arrange three integers and output them after sorting from small to large.

Sample input: 20, 7, 33

Sample output: 7, 20, 33



1. The first output

#include<stdio.h>
#include<stdlib.h>
int main(){
  int a,b,c;
  int s;
  scanf("%d%d%d",&a,&b,&c);
  if(a>b){
          s=a;
          a=b;
          b=s;
          }
  if(c<a){
          printf("%d %d %d\n",c,a,b);
          }
          if(c>b){
                  printf("%d %d %d\n",a,b,c);
                  }
          else{
               printf("%d %d %d\n",a,c,b);
               }
  system("pause");
  return 0;

The disadvantage is that it does not take into account the situation when the three input numbers are the same size.

2. Refer to the examples in the book

#include<stdio.h>
#include<stdlib.h>
int main(){
   int a,b,c;
   scanf("%d %d %d",&a,&b,&c);
   if(c<=b&&b<=a)printf("%d %d %d\n",c,b,a);
   else if(a<=b&&b<=c)printf("%d %d %d\n",a,b,c);
   else if(a<=c&&c<=b)printf("%d %d %d\n",a,c,b);
   else if(b<=c&&c<=a)printf("%d %d %d\n",b,c,a);
   else if(b<=a&&a<=c)printf("%d %d %d\n",b,a,c);
   else if(c<=a&&a<=b)printf("%d %d %d\n",c,a,b);
 
   system("pause");
   return 0;
}


The direction logic of the program is not clear at the beginning. In fact, the centralized arrangement of the three numbers a, b, and c should be listed, and then sorted out. There is an error in the middle, because if(b<c&&a<c)printf("%d %d %d\n",b,c,a); the program seems to stop when it runs here, so there is no output.

The first improvement: it is the correction of the above error;

The second improvement: Because it is simply greater than or less than the situation when the input is "1 1 1" cannot be determined, so the "=" equal sign is added to the determination condition. --------- still can't output 1 1 1 correctly, the result is 6 111 output

The third improvement: adding else in front of if, the output is correct.


Conclusion: to consider comprehensively


3. Relatively simple procedure

#include<stdio.h>
#include<stdlib.h>
int main(){
  int a,b,c,t;
  scanf("%d%d%d",&a,&b,&c);
  if(a>c){
          t=a;
          a=c;
          c=a;
          }
  if(b<a){
          t=a;
          a=b;
          b=t;
          }
  if(c<b){
          t=b;
          b=c;
          c=t;
          }
  printf("%d %d %d\n",a,b,c);
  system("pause");
  return 0;
}




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325666970&siteId=291194637