C++ primer 第五版 第四章练习答案

4.6

#include "stdafx.h"
#include<iostream>
using namespace std;
int main() {
	int a=0;
	cin >> a;
	if (a % 2 == 0) {
		cout << "偶数"<< endl;
	
	}else {
		cout << "奇数" << endl;

	}
}


4.7

1----指针溢出

#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;
int main() {
	int a[3] = { 0,0,0 };
	for (auto q = a; q != a+5; ++q) {
		cout << *q << endl;
	}

	
}

2----unsigned溢出

#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;
int main() {
	int a = 20;
	unsigned int b = a / -5;
	cout << b << endl;

	
}

3----short溢出

#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;
int main() {
	short a = 32768;
	
}

4.10

#include<iostream>
using namespace std;
int main() {
	int a = 0;
	while (cin>>a && a!=42) {
		cout << "yes" << endl;
}
}

4.11

#include<iostream>
using namespace std;
int main() {
	int a=5, b=4, c=3, d=2;
	if (a > b && b > c && c > d) {
		cout << "符合" << endl;
}
}

4.21

#include<iostream>
using namespace std;
int main() {
	int a=5, b=4, c=3, d=2;
	if (a > b && b > c && c > d) {
		cout << "符合" << endl;
}
}

4.22

1----使用多个if

#include<iostream>
#include<vector>
using std::vector;
using namespace std;
int main() {
	int grade;
	cin >> grade;
	if (grade >= 90) {
		cout << "high pass";
	}
	else {
		if (grade >= 75) {
			cout << "pass";
		}
		else {
			if (grade >= 60) {
				cout << "low pass";
			}
			else {
				cout << "fail";
			}
		}
	}
}

2----只使用条件运算符

#include<iostream>
#include<vector>
using std::vector;
using namespace std;
int main() {
	int grade;
	cin >> grade;
	cout << ((grade >= 90) ? ("high pass") : (grade >= 75) ? ("pass") : (grade >= 60) ? ("low pass") : ("fail"));
}

4.28

#include<iostream>
using namespace std;
int main() {
	cout << sizeof(bool) << endl;
	cout << sizeof(char) << endl;
	cout << sizeof(wchar_t) << endl;
	cout << sizeof(char16_t) << endl;
	cout << sizeof(float) << endl;
	cout << sizeof(double) << endl;
	cout << sizeof(long double) << endl;
}

4.29

#include<iostream>
using namespace std;
int main() {
	int a[10]; int*p = a;
	cout << sizeof(a) / sizeof(*a) << endl;;
	cout << sizeof(p) / sizeof(*p);
}

4.31

#include<iostream>
using namespace std;
#include<vector>
int main() {
	vector<int>ivec = { 0,1,2 };
	vector<int>::size_type cnt = ivec.size();
	for (vector<int>::size_type ix = 0; ix != ivec.size();) {
		ivec[ix++] = cnt--;
	}
	for (auto q : ivec) {
		cout << q << endl;
	}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值