zoukankan      html  css  js  c++  java
  • 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);
    }

    真正完结撒花。

  • 相关阅读:
    国密SM4,javaScript加密 java解密
    使用Nexus搭建Maven私服
    eclipse中使用Maven创建Web项目
    mysql报错码code=exited,status=2的解决方案
    Git出现 fatal: Pathspec 'xxx' is in submodule 'xxx' 异常的解决方案
    php使用ZipArchive提示Fatal error: Class ZipArchive not found in的解决方法
    (转)Git操作
    apt update时出现签名无法验证,公钥失效的解决办法
    提交项目到Github
    分解关联查询
  • 原文地址:https://www.cnblogs.com/lbssxz/p/13121648.html
Copyright © 2011-2022 走看看