发布后就很丢人的随笔(c++)

时间:2023-03-08 22:13:05
发布后就很丢人的随笔(c++)

for循环条件中使用的变量

  • 可以是循环条件中定义的变量
  • 也可以是循环之外的变量
  • 代码:
#include <iostream>

int main(){
    int a = 1;
    int b = 1;
    int c = 1;
    int d = 0;
    d += a + b + c;
    std::cout << d << std::endl;
    for(int i = 0; i < 10; i += a + 1) {
        int a = 10;
        std::cout << "i: " << i << std::endl;
    }
}
  • 输出:
3
i: 0
i: 2
i: 4
i: 6
i: 8

除数为0

  • 整形除数真的为0
  • 实形除数近似为0
  • 代码:
#include <iostream>

int main(){
{
    int a = 0;
    int b = 1;
    b / a;
    std::cout << "b / a is ok" << std::endl;

    if( b / (float)a >= 0.05 ){
        std::cout << "b / (float)a >= 0.05 is ok" << std::endl;
        std::cout << b / (float)a << std::endl;
    }

    if( b / (double)a >= 0.05 ){
        std::cout << "b / (double)a >= 0.05 is ok" << std::endl;
        std::cout << b / (double)a << std::endl;
    }

/*
core dump
    std::cout << b/a << std::endl;

    if( b / a > 0.05 ){
        std::cout << "b / a > 0.05 is ok" << std::endl;
    }
*/
}
std::cout << "--------------------------------" << std::endl;
{
    float a = 0;
    int b = 1;
    b / a;
    std::cout << "b / a is ok" << std::endl;

    if( b / (float)a >= 0.05 ){
        std::cout << "b / (float)a >= 0.05 is ok" << std::endl;
        std::cout << b / (float)a << std::endl;
    }

    if( b / (double)a >= 0.05 ){
        std::cout << "b / (double)a >= 0.05 is ok" << std::endl;
        std::cout << b / (double)a << std::endl;
    }

    // std::cout << b/a << std::endl;; // core dump

    if( b / a > 0.05 ){
        if( a == 0 ) std::cout << "a(float) is 0" << std::endl;
        std::cout << "b / a > 0.05 is ok" << std::endl;
    }
}
}
  • 结果
b / a is ok
b / (float)a >= 0.05 is ok
inf
b / (double)a >= 0.05 is ok
inf
--------------------------------
b / a is ok
b / (float)a >= 0.05 is ok
inf
b / (double)a >= 0.05 is ok
inf
a(float) is 0
b / a > 0.05 is ok

nohup执行,重定向标准输出到x.log,一定会生成x.log文件,根据是否生成文件判断是否调用了启动脚本