4.2 算术运算符

本文深入探讨了C++中的各种运算符,包括一元运算符、溢出处理、算术表达式的计算顺序及整数除法的特点。通过具体的代码示例,详细解析了真值、负数、短整型溢出、算术运算以及整数除法的处理方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

书中页数:P124
代码名称:unaryOps.cc overflow.cc arith-ex.cc int-div.cc

//unaryOps.cc
#include <iostream>
using std::cout; using std::endl;

int main()
{
	int i = 1024;
	int k = -i; // i is -1024
	
	bool b = true;
	bool b2 = -b; // b2 is true!
	
	cout << b << " " << b2 << " " << endl;
	
	return 0;
}

// overflow.cc 
#include <iostream>
using std::cout; using std::endl;

int main() 
{
	short short_value = 32767; // max value if shorts are 16 bits

	short_value += 1; // this calculation overflows
	cout << "short_value: " << short_value << endl;

    return 0;
}

// arith-ex.cc
#include <iostream>
using std::cout; using std::endl;

int main()
{
	cout << -30 * 3 + 21 / 5 << endl;
	
	cout << -30 + 3 * 21 / 5 << endl;
	
	cout << 30 / 3 * 21 % 5 << endl;
	
	cout << 30 / 3 * 21 % 4 << endl;
	
	cout << -30 / 3 * 21 % 4 << endl;
	
	cout << 12 / 3 * 4 + 5 * 15 + 24 % 4 / 2 << endl;
	
	return 0;
}

//int-div.cc
#include <iostream>
using std::cout; using std::endl;

int main() 
{
	// ival1 is 3; result is truncated; remainder is discarded
	int ival1 = 21/6;

	// ival2 is 3; no remainder; result is an integral value
	int ival2 = 21/7;

	cout << ival1 << " " << ival2 << endl;

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值