• P5712 【深基3.例4】Apples 题解


    有关三目运算符总目录点这里

    三目运算符大法好

    代码:

    #include<cstdio>
    #include<iostream>
    #include<cstring>
    #include<cmath>
    #define ll long long
    #define re register
    using namespace std;
    inline int read()
    {
        int x=0,f=1; char ch=getchar();
        while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
        while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
        return x*f;
    }
    int x;
    char c1[5]={'a','p','p','l','e'};
    char p1[6]={'a','p','p','l','e','s'};
    int main()
    {
        x=read();
        printf("Today, I ate %d %s.",x,x>=2?p1:c1);
    }

    完结。


    个鬼啊?这题没完呢;

    这里涉及很重要的知识:

    这份代码的输出以及判定条件没问题,char数组确认没问题,但是,当我们带入1的时候,我们会发现系统给我们了这样一个答案:

     再确认一遍,三目运算符判定没有问题。

    于是我叫来了同机房的巨佬们一起研究错在哪里,甚至通过摄像头惊动了教练

    然而没找出来哪里错了。

    后来多方求助,找了出来:

    c1,p1数组开小了,我开的是正好卡大小上界的。然而在这个字符串的结尾会自动保存一个作为结束符号。而我的数组恰恰少了那一个符号,于是在访问的时候,内存访问溢出了,访问到下一个字符串的存储地址(很明显系统把他俩的内存地址安排到一块了),就认定为一个字符串一起输出了。。。

    打个红题还能找出自己基础知识的不足

    正确代码:

    #include<cstdio>
    #include<iostream>
    #include<cstring>
    #include<cmath>
    #define ll long long
    #define re register
    using namespace std;
    inline int read()
    {
        int x=0,f=1; char ch=getchar();
        while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
        while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
        return x*f;
    }
    int x;
    char c1[10]={'a','p','p','l','e'};//开大一点没坏处
    char p1[10]={'a','p','p','l','e','s'};
    int main()
    {
        x=read();
        printf("Today, I ate %d %s.",x,x>=2?p1:c1);
    }

    真正完结撒花。

  • 相关阅读:
    zsh设置显示路径
    mysql性能优化
    php实现网络请求的方法及函数总结
    AI面试机器人后端架构实践
    Python脚本遍历文件夹,检查文件版本是否存在
    将 VS Code 终端设置为始终以管理员权限打开
    python20220623
    python20220625
    ss命令详解
    python20220624
  • 原文地址:https://www.cnblogs.com/lbssxz/p/13121648.html
Copyright © 2020-2023  润新知