运算符
1.算数运算符
注意点:
1.整数相除,还是整型,负责为实型;
2.前置和后置的区别,赋值规则不同;
3.除和模的分母不能为0;
4.小数不能取余;
#include <iostream>
using namespace std;
int main()
{
int a = 8;
int b = 3;
float c = 3.0f;
cout << a + b << endl;
cout << a/b << " VS " << a/c << endl;
++a;
cout << "a : " << a << endl;
a++;
cout << "a : " << a;
return 0;
}
2.赋值运算符
3.比较运算符
注意:在cout时候,需要加括号
#include <iostream>
using namespace std;
int main()
{
int a = 10; int b = 20; int c = 10;
cout << (a == b) << endl;
bool d = a==c;
cout << d << endl;
return 0;
}
4.逻辑运算符
(&&,||)相当于python的(and,or)。对于!,记住非0都是真。
程序流程符号
5.选择结构
if语句,比python的if多括号,更加完整。因为python的每一行的缩进都是固定的,而c++不需要缩进。
#include <iostream>
using namespace std;
int main()
{
int a;
cin >> a;
if (a > 90)
{
cout << "score is enough\n";
}
else if ( a > 80)
{
cout << "score is danger\n";
}
else
{
cout << "score is bad\n";
}
return 0;
}
三目运算符
相当于python的:表达式2 if 表达式1 else 表达式3
注意:要加括号才能赋值
#include <iostream>
using namespace std;
int main()
{
int a = 10;
int b = 20;
int c = 30;
int d = a ? b : c;
cout << "d : " << d << endl; // d : 20
// 三目运算符也能赋值
(a>b ? b : c) = 100;
cout << "a : " << a << endl; // a : 10
cout << "b : " << b << endl; // b :
cout << "c : " << c << endl; // c :
return 0;
}
switch语句
#include <iostream>
using namespace std;
int main()
{
int x = 10;
switch (x)
{
case 10:
cout << "10\n";
break;
case 9:
cout << "9\n";
break;
default:
cout << "no\n";
break;
}
return 0;
}
6.循环结构
6.1while语句
与python一模一样
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
srand(time(0));
int x = rand() % 100 + 1; // 1-100
int y;
cin >> y;
while (x != y)
{
if (y > x)
{
cout << "bigger\n";
}
else
{
cout << "smaller\n";
}
cin >> y;
}
cout << "sucess\n";
return 0;
}
6.2do while语句
先进行,再判断;发现一个规律,大括号中写程序,圆括号中写判断。
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int x = 100;
int y = 0;
cout << "start" << endl;
do
{
int x1,x2,x3;
x1 = pow(x / 100, 3);
x2 = pow(x % 100 / 10, 3);
x3 = pow(x % 10, 3);
if (x1+x2+x3 == x)
{
++y;
cout << x1 << " " << x2 << " " << x3 << " : " << x << endl;
}
++x;
}while (x < 1000);
cout << "num is " << y << endl;
return 0;
}
6.3for语句
注意:
1. for的圆括号中,使用;间隔
2. 流程是从起始表达式开始,条件成立后运行语句,再经过末尾循环体,重复判断条件表达式。
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
for (int i = 1; i < 101; i++)
{
int x1,x2;
x1 = i % 10;
x2 = i / 10;
if (x1 == 7 || x2 == 7 || i % 7 == 0)
{
cout << i << endl;
}
}
return 0;
}
6.4嵌套循环
冷饭新炒;
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i < 11; i++ )
{
for (int i = 1; i < 11; i++ )
{
cout << "* ";
}
cout << "\n";
}
for (int i = 1; i <= 9; i++)
{
for (int j = 1; j <= i; j++)
{
cout << j << " * " << i << " = " << i*j << " | ";
}
cout << "\n";
}
return 0;
}
7.break,continue,以及goto
break和continue与python中的函数一样
goto
#include <iostream>
using namespace std;
int main()
{
cout << "1" << endl;
goto FLAG;
for (int i = 1; i < 10; i++)
{
cout << i << endl;
}
FLAG:
cout << "2" << endl;
}