【C++入门】(一)C++入门

一. 编写一个简单的C++程序——手速练习

#include <iostream>
using namespace std;

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

 

二. 语法基础

2.1 变量的定义

  • 变量必须先定义,才可以使用
  • 不能重名
复制代码
#include <iostream>
using namespace std;

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

    return 0;
}
复制代码

 

2.2 常用变量类型及范围

 

 

2.3 输入输出

复制代码
//整数的输入输出:
#include <iostream>
using namespace std;

int main()
{
    int a, b;
    cin >> a >> b;
    cout << a + b << endl;
    return 0;
}
复制代码
复制代码
//字符串的输入输出:
#include <iostream>
#include <string>
using namespace std;

int main()
{
    string str;
    cin >> str;
    cout << str;
    return 0;
}
复制代码
复制代码
//输入输出多个不同类型的变量:
#include <iostream>
#include <string>
using namespace std;

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

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

    cout << str << " !!! " << a + b << endl;

    return 0;
}
复制代码

 

2.4 表达式

 

复制代码
//整数的加减乘除四则运算:
#include <iostream>
#include <string>
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>
#include <string>
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>
#include <string>
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>
#include <string>
using namespace std;

int main()
{
    float x = 123.12;

    int y = (int)x;

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

    return 0;
}
复制代码

 

posted @   哟吼--小文文公主  阅读(69)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示