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;
    }
  • 相关阅读:
    stm32之不定长接收
    3、列表和列表项
    2、FreeRTOS任务相关API函数
    1、FreeRTOS移植
    5、根文件系统原理
    1、c++对c语言的扩展
    4、移植三星官方内核
    3、内核的启动过程
    2、内核的配置和移植
    iOS学习笔记19-地图(一)定位CoreLocation
  • 原文地址:https://www.cnblogs.com/JMDWQ/p/2354731.html
Copyright © 2011-2022 走看看