C(C++)语言(一)

C(C++)语言(一)

一个简单的程序

#include <iostream>

using namespace std;

int main()
{
    cout << "Hello World";
    return 0;
}

认识变量

变量是程序中最常见也是必不可少的因素

变量必须先定义,再去应用,且不能重名

变量定义的方式

#include <iostream>

using namespace std;

int main()
{
//  e = 1;
    int a = 5;
//  int a = 1;
    int b, c = a, d = 10 / 2;

    return 0;
}

4.png

输入输出

整数的输入输出:

#include <iostream>

using namespace std;

int main()
{
    int a, b;
//    cin >> a >> b;
//    cout << a + b << endl;
    scanf("%d%d", &a, &b); 
    printf("%d", a + b);
    return 0;
}

字符串的输入输出:

#include <iostream>

using namespace std;

int main()
{
    string s1;
    cin >> s1;
    cout << s1;
//  scanf("%s", &s1[0]); 
//  printf("%s", s1.c_str());
    return 0;
}

输入输出多个不同类型的变量:

#include <iostream>

using namespace std;

int main()
{
    int a, b;
    string str;

    cin >> a;
    cin >> b >> str;

    cout << str << " !!! " << a + b << endl;
    printf("%s !!! %d", str.c_str(), a + b);

    return 0;
}

表达式

5.png

整数的加减乘除四则运算:

#include <iostream>

using namespace std;

int main()
{
    int a = 6 + 3 * 4 / 2 - 2;

    cout << a << endl;

    int b = a * 10 + 5 / 2;

    cout << b << endl;

    cout << 23 * 56 - 78 / 3 << endl;

    return 0;
}

浮点数(小数)的运算:

#include <iostream>

using namespace std;

int main()
{
    float x = 1.5, y = 3.2;

    cout << x * y << ' ' << x + y << endl;

    cout << x - y << ' ' << x / y << endl;

    return 0;
}

整型变量的自增、自减:

#include <iostream>

using namespace std;

int main()
{
    int a = 1;
    int b = a ++ ;

    cout << a << ' ' << b << endl;

    int c = ++ a;

    cout << a << ' ' << c << endl;

    return 0;
}

变量的类型转换:

#include <iostream>

using namespace std;

int main()
{
    float x = 123.12;

    int y = (int)x;

    cout << x << ' ' << y << endl;

    return 0;
}

题外话

代码规范

1.

#include<bits/stdc++.h>
using namespace std;
int main(){
    int a,b;cin>>a>>b;
    cout<<a+b<<endl;
    return 0;
}

2.

#include <iostream>

using namespace std;

int main()
{
    int a, b;
    cin >> a >> b;
    cout << a + b;
    return 0;
}

学会编程练习的时间要绝对大于看视频时间!!!

练习地址题单广场 – 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

上一篇
下一篇