C++ Primer习题解答 Chapter 4

4-21

#include<iostream>
#include<vector>
using namespace std;

int main()
{
	vector<int> vint;
	const int sz = 100;
	cout << "原向量:" << endl;
	for (int i = 0; i < sz; i++) {
		vint.push_back(i);
		cout << i << " ";
	}
	cout << endl;
	cout << "新向量:" << endl;
	for (auto &i : vint) {
		i = i % 2 != 0 ? i * 2 : i;
		cout << i << " ";
	}
	cout << endl;
	system("pause");
}

4-22

#include<iostream>
#include<string>
using namespace std;
int main()
{
	string result;
	unsigned int grade;
	while (cin >> grade) {
		if (grade <= 100) {
			result = grade >= 90 ? "high pass" : grade >= 75 ? "pass" :
				grade >= 60 ? "low pass" : "failure";
			cout << "条件表达式:" << result << endl;
			if (grade >= 90) {
				result = "high pass";
			}
			else if (grade >= 75) {
				result = "pass";
			}
			else if (grade >= 60) {
				result = "low pass";
			}
			else {
				result = "failure";
			}
			cout << "分支结构:" << result << endl;
		}
	}
	system("pause");
}

4-28

#include<iostream>
#include<string>
using namespace std;
int main()
{
	cout << "short:\t\t" << sizeof(short) << endl;
	cout << "int:\t\t" << sizeof(int) << endl;
	cout << "long:\t\t" << sizeof(long) << endl;
	cout << "long long:\t" << sizeof(long long) << endl;
	cout << "char:\t\t" << sizeof(char) << endl;
	cout << "wchar_t:\t" << sizeof(wchar_t) << endl;
	cout << "char16_t:\t" << sizeof(char16_t) << endl;
	cout << "char32_t:\t" << sizeof(char32_t) << endl;
	cout << "bool:\t\t" << sizeof(bool) << endl;
	cout << "float:\t\t" << sizeof(float) << endl;
	cout << "double:\t\t" << sizeof(double) << endl;
	cout << "long double:\t" << sizeof(long double) << endl;
	system("pause");
}

4-37

把旧式的类型转换改成命名强制类型转换比较简单,观察转换前后的类型即可,如果涉及到类型变化就用static_cast<>(),如果涉及到去掉底层const就使用const_cast<>()

#include<iostream>
#include<string>
using namespace std;
int main()
{
	int i;
	double d;
	const string *ps;
	char *pc;
	void *pv;
	//pv = (void*)ps;
	pv = static_cast<void*>(const_cast<string*>(ps));
	//i = int(*pc);
	i = static_cast<int>(*pc);
	//pv = &d;
	pv = static_cast<void*>(&d);
	//pc = (char*) pv;
	pc = static_cast<char*>(pv);
	system("pause");
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值