01输入输出&变量
2025年2月15日...大约 2 分钟
01输入输出&变量
注
免责声明
本站收录的所有c++课程,均为博主上竞赛课时得到的课件,仅作学习交流使用,无任何盈利或商业用途,也请贵客勿将其作为商业用途。
编写一个简单的C++程序
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World" << endl;
return 0;
}
语法基础
- 变量定义
注
变量必须先定义,才可以使用。不能重名。
变量定义的方式:
#include <iostream>
using namespace std;
int main()
{
int a = 5;
int b, c = a, d = 10 + 2;
return 0;
}
常用变量类型及范围:
类型 | 范围 |
---|---|
int | -2^31 ~ 2^31 - 1 |
long long | -2^63 ~ 2^63 - 1 |
double | Approximately 2^-1022 ~ 2^1023 |
bool | true (1), false (0) |
- 输入输出
整数的输入输出:
#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;
}
- 高效输入输出
在处理大量数据时,CSP-S 比赛中使用以下技巧来加快输入输出速度:
- 关闭输入输出的同步:
ios::sync_with_stdio(false);
cin.tie(0);
这可以显著加快cin
和cout
的效率。
- 使用
scanf
和printf
进行输入输出,特别是在需要处理大量数据时:
#include <cstdio>
int main()
{
int a, b;
scanf("%d %d", &a, &b);
printf("%d", a + b);
return 0;
}
- 表达式与运算符
整数的加减乘除四则运算:
#include <iostream>
using namespace std;
int main()
{
int a = 10, b = 3;
cout << "Sum: " << a + b << endl;
cout << "Difference: " << a - b << endl;
cout << "Product: " << a * b << endl;
cout << "Quotient: " << a / b << endl; // 整数除法
cout << "Remainder: " << a % b << endl; // 求余数
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
getline(cin, str); // 读取整行
cout << str << endl;
return 0;
}
- 注意运算符的优先级,复杂表达式中使用括号确保运算顺序。
模运算 %
常用于处理循环问题,例如大数模运算。
- 输入输出技巧与常见问题
处理包含空格的字符串:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
getline(cin, str); // 读取整行
cout << str << endl;
return 0;
}
- 输入异常处理:确保输入的格式正确,如果输入不符合预期,CSP-S 可能会出现错误数据处理问题,需要特别小心。