CPP Tutorials for Beginners

发布时间 2023-09-23 23:45:00作者: Egu0

CPP Tutorials for Beginners, Mosh, Youtube

IDE: CLion
Env: C++20

#include <iostream>
#include <cmath>
#include <cstdlib>

void const_var();

void create_var();

void math_calculate();

void read_from_input();

void use_standard_lib();

void sizeof_types();

void working_with_number();

using namespace std;

int main() {
//    create_var();
//    const_var();
//    math_calculate();
//    read_from_input();
//    use_standard_lib();
//    sizeof_types();
//    working_with_number();

    // narrowing
    short s = 10'0000;
    int i = s;
    int j{s}; // brace initializer
    cout << s << endl << i << endl << j << endl;

    // random
    srand(time(0));
    for (int k = 0; k < 10; ++k) {
        int no = rand();
        cout << "random number:" << no << endl;
    }

    return 0;
}

/**
 * @code <pre>
    bool: 1
    char: 1
    ----
    short: 2
    int: 4
    long: 8
    long long: 8
    ----
    float: 4
    double: 8
 * </pre>
 *
 */
void sizeof_types() {
    short s = 1;
    int i = 1;
    long l = 1;
    long long ll = 1;
    float f = 1.1;
    double d = 1.1;
    bool b = false;
    char c = 'a';
    cout << "short: " << sizeof s << endl;
    cout << "int: " << sizeof i << endl;
    cout << "long: " << sizeof l << endl;
    cout << "long long: " << sizeof ll << endl;
    cout << "float: " << sizeof f << endl;
    cout << "double: " << sizeof d << endl;
    cout << "bool: " << sizeof b << endl;
    cout << "char: " << sizeof c << endl;
}

void working_with_number() {
    float f = 3.28F;
    long l = 2000L;
    char c = 'a';
    bool b = true;
//    auto x;
    auto y = 1; // default number type is integer

    int num1 = 0b11111111; // 255
    int num2 = 0x0001; // 1
    int num3 = -230;
    cout << num1 << endl << num2 << endl << num3 << endl;

    unsigned int u1 = 0;
    u1--;
    cout << u1 << endl; // 4294967295
}

void use_standard_lib() {
    // cmath reference: https://cplusplus.com/reference/cmath/
    cout << sqrt(4.2) << endl;
}

void read_from_input() {
    int value;
    cout << "pls input a integer num:";
    cin >> value;
    cout << "input value is: " << value << endl;
    cout << "input 2 num to add:";
    int n1, n2;
    cin >> n1 >> n2;
    cout << "n1 + n2 = " << n1 + n2 << endl;
}

void math_calculate() {
    int n1 = 10;
    double n2 = 3.1;
    double x = n1 / n2;
    cout << x << endl;

    int a = 10;
    cout << a++ << endl;
    cout << ++a << endl;

    double b = 1 + 2 * 3;
    cout << b << endl;

    const double taxRate = .02; // 0.02
    cout << "Tax : $" << 2000 * taxRate << endl;

}

void create_var() {
    int file_size = 100;
    cout << file_size << endl;
}

void const_var() {
    // use const keyword to mark unmodifiable variable
    const double PI = 3.1415926;
    // PI = 1;
}