zoukankan      html  css  js  c++  java
  • C语言的一个关于类型的小陷阱

    类型的差别造成奇怪的运行结果——输出错误、无法继续输入等

    新增:

    找出下面代码的错误:

    # include <stdio.h>
    # include <string.h>

    # define MAXN 10005

    int main()
    {
    short m, n, i, ans, tmp, t[MAXN];

    while (~scanf("%d%d", &n, &m))
    {
    memset(t, 0, sizeof(t));
    for (i = 1; i <= m; ++i)
    {
    scanf("%d", &tmp);
    t[tmp] = t[tmp]+1;
    }
    ans = tmp = 0;
    for (i = 1; i <= n; ++i)
    if (t[i] > tmp)
    {
    tmp = t[i];
    ans = i;
    }
    printf("%d\n", ans);
    }

    return 0;
    }

    题一:输入两个实数(0~1000),输出它们的和,并保留四位小数(多组输入)。

    wrong
    # include <stdio.h>
    int main()
    {
    double a,b;
    while (scanf("%f%f", &a,&b))
    printf("%.4f\n", a+b);
    return 0;
    }
    right
    # include <stdio.h>
    int main()
    {
    double a,b;
    while (scanf("%lf%lf", &a,&b))
    printf("%.4lf\n", a+b);
    return 0;
    }

    题二:输入两个整数(0~1000),输出它们的和(多组输入)。

    wrong
    # include <stdio.h>
    int main()
    {
    short int a,b;
    while (scanf("%d%d", &a,&b))
    printf("%d\n", a+b);
    return 0;
    }
    right
    # include <stdio.h>
    int main()
    {
    int a,b;
    while (scanf("%d%d", &a,&b))
    printf("%d\n", a+b);
    return 0;
    }

    找出下列代码错误之处:

    wrong
    // 1003 UC Browser
    # include <stdio.h>
    # define MAXN 105
    short int expr[] = {0,1,3,6,10,15};
    int main()
    {
    short int T, n, tot, cnt, i;
    char a[MAXN];
    scanf("%d", &T);
    while (T > 0)
    {
    scanf("%d%s", &n,a);
    tot = 0;
    for (i=0; i<n; ++i)
    {
    cnt = 0;
    while ('1'==a[i]){++cnt;++i;}
    tot += (cnt/5)*15+expr[cnt%5];
    }
    printf("%d\n",(tot<75 ? (tot+5)/10:8));
    --T;
    }
    return 0;
    }

    正确的在这里:

    right
    // 1003 UC Browser
    # include <stdio.h>
    # define MAXN 105
    short int expr[] = {0,1,3,6,10,15};
    int main()
    {
    int T, n, tot, cnt, i; // short int 改为 int
    char a[MAXN];
    scanf("%d", &T);
    while (T > 0)
    {
    scanf("%d%s", &n,a);
    tot = 0;
    for (i=0; i<n; ++i)
    {
    cnt = 0;
    while ('1'==a[i]){++cnt;++i;}
    tot += (cnt/5)*15+expr[cnt%5];
    }
    printf("%d\n",(tot<75 ? (tot+5)/10:8));
    --T;
    }
    return 0;
    }
  • 相关阅读:
    项目成本管理(三)
    项目成本管理(二)
    项目成本管理(一)
    男士香水
    荷兰猛兽-梅尔文训练体能
    PP学习笔记-业务基础
    SAP入行就业
    PP学习笔记02
    BZOJ 3012: [Usaco2012 Dec]First! 字典树 + tarjan
    CF319E Ping-Pong 线段树 + vector + 思维
  • 原文地址:https://www.cnblogs.com/JMDWQ/p/2354731.html
Copyright © 2011-2022 走看看