• csu 1214 三个数字


    1、2、3三个数字组成的序列,要求把所有的2放在前面,所有的3放在后面,输出结果。

    下面的代码提交了好几次(修改不大)都是WA,错误的原因是输入结束(EOF)前不一定有换行,这样最后一组测试数据就没法输出 1 和 3。

     1 # include <stdio.h>
    2
    3 char ch;
    4 int cnt1, cnt3;
    5
    6 int main()
    7 {
    8 while ((ch=getchar()) != EOF)
    9 {
    10 if (ch == '2') putchar(ch);
    11 else if (ch == '1') ++cnt1;
    12 else if (ch == '3') ++cnt3;
    13 else if (ch == '\n')
    14 {
    15 while (cnt1) {putchar('1');--cnt1;}
    16 while (cnt3) {putchar('3');--cnt3;}
    17 putchar(ch);
    18 }
    19 }
    20
    21 return 0;
    22 }

    打补丁的做法(AC):

     1 # include <stdio.h>
    2
    3 char ch;
    4 int cnt1, cnt3;
    5
    6 int main()
    7 {
    8 //freopen("in.txt", "r", stdin);
    9 //freopen("out.txt", "w", stdout);
    10
    11 while ((ch=getchar()) != EOF)
    12 {
    13 if (ch == '2') putchar(ch);
    14 else if (ch == '1') ++cnt1;
    15 else if (ch == '3') ++cnt3;
    16 else if (ch=='\n')
    17 {
    18 while (cnt1) {putchar('1');--cnt1;}
    19 while (cnt3) {putchar('3');--cnt3;}
    20 putchar(ch);
    21 }
    22 }
    23 while (cnt1) {putchar('1');--cnt1;}
    24 while (cnt3) {putchar('3');--cnt3;}
    25
    26 return 0;
    27 }

    修改一下结构:

     1 # include <stdio.h>
    2
    3 char ch;
    4 int cnt1, cnt3;
    5
    6 int main()
    7 {
    8 // freopen("in.txt", "r", stdin);
    9   // freopen("out.txt", "w", stdout);
    10
    11 while ((ch=getchar()))
    12 {
    13 if (ch == '2') putchar(ch);
    14 else if (ch == '1') ++cnt1;
    15 else if (ch == '3') ++cnt3;
    16 else
    17 {
    18 while (cnt1) {putchar('1');--cnt1;}
    19 while (cnt3) {putchar('3');--cnt3;}
    20 if (ch=='\n') putchar(ch);
    21 else break;
    22 }
    23 }
    24
    25 return 0;
    26 }
  • 相关阅读:
    对宏的另外一些认识 及 assert.h的实现细节
    不要想太多
    线段树
    SQL基础 利用SELECT检索数据
    hidden表单值无法重置的缺陷
    oracle 数据库登陆
    基于ejb3,对JDBC进行封装,让使用JDBC时能像hibernate使用annotation注解一样简便,而且更加轻巧
    GoJS的一些使用技巧
    GoJS的学习使用
    灵活使用trim方法
  • 原文地址:https://www.cnblogs.com/JMDWQ/p/2391647.html
Copyright © 2020-2023  润新知