1.1 变量、输入输出、表达式和顺序语句
#include <cstdio> //printf,scanf
#include <iostream> //cin,cout 不用判断数据的输入输出类型
using namespace std; //命名空间
int main() //函数的入口
{
cout<<"Hello World!"<<endl;
return 0;
}
常用变量类型及范围:
类型 | 关键字 | 注释 | 大小 |
---|---|---|---|
布尔型 | bool | false/true | 1byte |
字符型 | char | ‘c’,’ ', '/n’一个字符用单引号 | 1byte |
整型 | int | -2147483648~214783647;-231 ~231-1 | 4byte |
浮点型 | float | 6-7位有效数字 | 4byte |
双浮点型 | double | 15-16位有效数字 | 8byte |
long long | -263 ~263-1 | 8byte | |
long double | 18-19位有效数字 | 16byte |
B->Byte 字节
b->bit 位
1Byte=8bit
1.变量的定义:
//变量的定义
int a, b=2, c=b;
float d=1.5, e=1, f=1.234e2;
bool g = true, h=false;
char j = 'a', k = 'b';
long long l=1000000000000ll;
long double m =123.45;
2.变量的输入输出:
#include <iostream>
using namespace std;
int main()
{
int a,b; //定义两个变量
cin >> a >> b; //输入
cout << a + b << endl; //输出
return 0;
}
输出多个变量:
#include <iostream>
using namespace std;
int main()
{
int a,b; //定义两个变量
cin >> a;
cin >> b; //输入
cout << a + b;
cout << ' ';
cout << a * b;
cout << endl; //输出
return 0;
}
使用scanf,printf进行输入输出:
#include <cstdio>
#include <iostream>
using namespace std;
int main() //函数的入口
{
int a,b; //定义两个变量
scanf("%d%d", &a, &b); // %f读入浮点数类型
// %d读入整数类型
// &取地址符号
// \n是回车
printf("a + b = %d\na * b = %d\n", a+b, a*b);
// 输出保留3位小数 %.3f
return 0;
}
//浮点数的输入输出
#include <cstdio>
#include <iostream>
using namespace std;
int main()
{
float a, b;//定义两个变量
scanf("%f%f",&a,&b);
printf( "a + b = %.1f\na * b = %.2f\n", a + b,a * b);
return 0;
}
//char的输入输出
#include <cstdio>
#include <iostream>
using namespace std;
int main()
{
char a, b; //定义两个变量
cin >> a >> b;
printf( "%c %c\n", a, b);
return 0;
}
//double的输入输出
#include <cstdio>
#include <iostream>
using namespace std;
int main()
{
double a, b; //定义两个变量
scanf("%lf%lf", &a, &b);
printf( "%lf %lf\n", a, b);
return 0;
}
//long long的输入输出
#include <cstdio>
#include <iostream>
using namespace std;
int main()
{
long long a, b; //定义两个变量
scanf("%lld%lld", &a, &b);
printf( "%lld %lld\n", a, b);
return 0;
}
scanf,printf输出效率比较高
cin,cout 不用判断数据的输入输出类型,cin会过滤空格
%c会读入空格需要过滤一下
#include 中对某个数字开平方 sqrt(x);
/*
int: %d
float: %f
double: %lf
char %c
long long %lld
*/
3.表达式
整数的加减乘除四则运算:
#include <cstdio>
#include <iostream>
using namespace std;
int main()
{
int a = 6;
int c = a ++; //a先给c然后再加1
cout << a << ' ' << c << endl;
int b = 6;
int d = ++ b; //b先加1再赋值给d
cout << b << ' ' << d << endl;
return 0;
}
简写运算:
b += a; b = b + a;
b -= a; b = b - a;
b *= a; b = b * a;
b /= a; b = b / a;
b %= a; b = b % a;
变量的强制转换:
#include <iostream>
#include <string>
using namespace std;
int main()
{
float x = 123.12;
int y = (int)x;
cout << x << ' ' << y << endl;
return 0;
}