Blogger Information
Blog 15
fans 0
comment 0
visits 9096
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
计算机的if 改为 switch
Original
1387 people have browsed it

2、计算机的if 改为 switch

  1. int x,y;
  2. scanf("%d",&x);
  3. if(x<5) {
  4. y=x;
  5. printf("x=%d, y=x %d\n",x,y);
  6. } else if(x<10) {
  7. y=2*x-1;
  8. printf("x=%d, y=2*x-1 %d\n",x,y);
  9. } else {
  10. y=3*x-11;
  11. printf("x=%d, y=3*x-11 %d\n",x,y);
  12. }

改成

  1. #include <stdio.h>
  2. int main(void) {
  3. int x, y;
  4. int c;
  5. scanf("%d", &x);
  6. c=(x<5)*1+(x>=5&&x<10)*2+(x>=10)*3;
  7. switch(c) {
  8. case 1:
  9. y = x;
  10. printf("x=%d, y=x = %d\n",x,y);
  11. break;
  12. case 2:
  13. y = 2*x-1;
  14. printf("x=%d, y=2*x-1 = %d\n",x,y);
  15. break;
  16. case 3:
  17. y = 3*x-11;
  18. printf("x=%d, y=3*x-11 = %d\n",x,y);
  19. break;
  20. }
  21. return 0;
  22. }
Correcting teacher:PHPzPHPz

Correction status:qualified

Teacher's comments:switch中,把+、-、*、/、%是否更加直观,不易犯错
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post