#include<iostream>
using namespace std;
int main()
{
int a1=10;
int b1=3;
cout << a1 / b1 << endl;
system("pause");
return 0;
}
1.和c语言一样,会输出3
,因为a1和b1都是定义的int型,所以输出会保留整型舍掉小数部分的,怎么才能输出小数的形式呢?
和c语言一样,强制转换:cout << (float)a1 / b1 << endl;
会输出3.33333
一共是6位有效数字,原因之前也解释了
2.取模(%)
int a3 = 3;
int b3 = 20;
cout << a3 % b3 << endl;
如果a与b运算取模,a%b中a<b,则结果等于a;
在C++中两个小数是不能取模的。
3.比较符号
真的话为1,假的话为0;
实例
#include<iostream>
using namespace std;
int main()
{
int a = 10;
int b =20;
cout << (a==b)<< endl;//0
cout << (a>b)<< endl;//0
cout << (a !=b) << endl;//1
cout << (a < b) << endl;//1
system("pause");
return 0;
}
4.逻辑运算符
4.1非运算
#include<iostream>
using namespace std;
int main()
{
//逻辑运算非!
int a = 10;
cout << a << endl;(输出为10)
//C++中除了都为真
cout << !a << endl;(输出为0)
cout << !!a << endl;(输出为1)
system("pause");
return 0;
}
4.2与运算
八字真言:同真为真,其余为假
int a1 = 10;
int a2 = 10;//不为0都为真
cout << (a1 && a2) << endl;//两个真与运算肯定也为真了
a1 = 10;
a2 = 0;//假
cout << (a1 && a2) << endl;//输出就为0
4.3逻辑或运算
八字真言:同假为假,其余位置真
int a = 10;
int b = 10;
cout << (a || b) << endl;
b = 0;
a = 10;
cout << (a || b) << endl;
a = 0;
b = 0;
cout << (a || b) << endl;
5.三目运算符
注意:C++中三目运算符返回的是变量,可以继续赋值
#include<iostream>
using namespace std;
int main()
{
int a = 10;
int b = 30;
int c = 0;
c = (a > b ? a : b);//c=30
//C++中三目运算符返回的是变量,可以继续赋值
cout << "a=" << a << endl;//10
cout << "b=" << b << endl;//30
cout << "c=" << c << endl;//30
(a > b ? a : b) = 100;//b=100
cout << "a=" << a << endl;//10
cout << "b=" << b << endl;//100
cout << "c=" << c << endl;//30
system("pause");
return 0;
}
6.continue语句
作用:在循环语句中,跳过本次循环中余下尚未执行的语句,继续执行下一次循环:
打印1到20的奇数
#include<iostream>
using namespace std;
int main()
{
//打印1到100的奇数
int i = 0;
for (i = 1; i <= 20; i++)
{
if (i % 2 == 0) {
continue;
}
cout << i << endl;
}
system("pause");
return 0;
}
7.goto语句
解释:如果标记的名称存在,执行到goto语句时,会跳转到标记的位置示例:
#include<iostream>
using namespace std;
int main()
{
cout << "1" << endl;
cout << "2" << endl;
goto B;
cout << "3" << endl;
cout << "4" << endl;
B:
cout << "5" << endl;
cout << "6" << endl;
system("pause");
return 0;
}