本篇将讲解C++中的int
类型变量和相对应的基础运算,这节课对于学习过其它语言的同学会很简单,所以这节课干货较多
int
类型变量int
类型变量前文有讲到,这里不多赘述,直接上干货
int a;//定义一个名为 a 的 int 类型变量
int b,c;//定义一个 a 和 b,用 , 分隔,并用 ; 结束本行
int d;int e;//分别定义 d 和 e,在一行(视觉)中使用 ; 分隔两行(程序意义上)
cout<<a;//输出变量 a
cout<<a+1<<endl;//输出a+1后的值,但a本身没有改变
cout<<a-1<<endl;//输出a-1的值,同上
cout<<a*1<<endl;//输出a乘1的值,同上
cout<<a/1<<endl;//输出a除1的值(是2而不是2.5),同上
a
是int
,因此/
的结果不可能是小数,可以这么理解:5÷2=2(这是结果)......1
cout<<a%1<<endl;//输出a÷1的余数,同上
cout<<a++<<endl;//输出a的值,因为是先调用再+1,改变了a本身
cout<<++a<<endl;//输出a+1的值,因为是先+1调用再调用,改变了a本身
//都可以单独拿出来用,如下
a++;++a;
a--;--a;//a-1,改变本身
a*=1;//a×1,同上
a/=1;//同上
a%=1;//a变为a÷1的余数
int result = 2 + 3 * 4; // 乘法优先,结果是14
//就像这样
1.整数溢出问题:
int max = 2147483647; // 通常int的最大值
max++; // 会导致溢出,变为-2147483648
2.除零问题
int a = 5 / 0; // 运行时错误
int b = 5 % 0; // 运行时错误
int a = 5 / 2;
执行后,变量a的值是______。int b = 10; b++;
执行后,b的值变为11。( )int a = 2147483647 + 1;
int b = 100 / 10;
int c = 5 % 2;
int d = 0 + 1;
编写一个程序,要求:
定义两个int类型变量a和b
给a赋值为15,b赋值为4
计算并输出a/b的结果和a%b的结果
最后对a执行自增操作(使用a++),并输出a的新值
1.2
2.正确
3.A
4.参考代码:
#include <iostream>
using namespace std;
int main() {
int a = 15, b = 4;
cout << "a/b = " << a/b << endl;
cout << "a%b = " << a%b << endl;
a++;
cout << "a after increment: " << a << endl;
return 0;
}
输出结果:
text
a/b = 3
a%b = 3
a after increment: 16
学完了就在评论区分享一下成果和做题情况吧