C++ Prime 第五章 语句

2023-03-17~2023-03-18

简单语句

  • 空语句:;当语法上需要一条语句但是程序逻辑上不需要时可以使用空语句
  • 空块:{}作用与空语句相等

5.1节练习

alt

  • 练习5.1、5.2如上诉
  • 练习5.3:
using namespace std;
#include<iostream>

int main()
{
	int sum = 0, val = 1;
	while (val < 10)
		sum += val, ++val;
	
	system("pause");
	return 0;
}

5.2节练习

alt

  • 练习5.4:
    (a):当iter这个迭代器不指向s的尾后指针时,循环执行块中的代码(最后块中需要添加循环结束条件的代码,不然将无线循环)
    (b):
using namespace std;
#include<iostream>

int main()
{
	while (bool status = find(word)) {
		;
	}
	if (!status) {
		;
	}
	system("pause");
	return 0;
}

语句作用域

  • 当if-else语句未使用块来包含逻辑代码时,并且存在多个if-else语句嵌套时,else会无视代码缩进与最近的一个if语句组合成if-else逻辑,所以当多个if-else嵌套时,需要使用块来包含相关的代码

5.3.1节练习

alt

  • 练习5.5:
using namespace std;
#include<iostream>
#include<vector>

int main()
{
	const vector<string> scores = { "F", "D", "C", "B", "A", "A++" };
	float score;
	while (cin >> score) {
		if (score < 60) {
			cout << score << "->" << scores[0] << endl;
		}
		else {
			if (score > 100) {
				score = 100;
			}
			cout << score << "->" << scores[(score - 50) / 10] << endl;
		}
	}
	system("pause");
	return 0;
}

  • 练习5.6:
using namespace std;
#include<iostream>
#include<vector>

int main()
{
	const vector<string> scores = { "F", "D", "C", "B", "A", "A++" };
	float score;
	while (cin >> score) {
		cout << (score < 60 ? scores[0] : 
			score > 100 ? scores[5] : scores[(score - 50) / 10]);
		cout << endl;
	}
	system("pause");
	return 0;
}

  • 练习5.7:
    (a)未加分号
using namespace std;
#include<iostream>

int main()
{
	int ival1, ival2;
	if (ival1 != ival2)
		ival1 = ival2;
	else ival1 = ival2 = 0;
	system("pause");
	return 0;
}

(b):多行代码时未使用块来包含代码

using namespace std;
#include<iostream>

int main()
{
	int ival, minval, occurs;
	if (ival < minval) {
		minval = ival;
		occurs = 1;
	}

	system("pause");
	return 0;
}

(c)=改为==,可以改写为if-else if

using namespace std;
#include<iostream>

int main()
{
	if (int ival == get_value()) {
		cout << "ival = " << ival << endl;
	}
	else if (!ival){
		cout << "ival = 0\n";
	}

	system("pause");
	return 0;
}

(d)=改为==

using namespace std;
#include<iostream>

int main()
{
	if (ival == 0)
		ival = get_value();
	system("pause");
	return 0;
}

###switch语句

  • case必须是整型常量
  • 可以将case组合起来来强调这些case值是属于一个范围内的值
using namespace std;
#include<iostream>

int main()
{
	int num = 4;
	switch (num)
	{
	case 1 : case 2 : case 3:
		cout << 1 << endl;
	default:
		break;
	}

	system("pause");
	return 0;
}

###switch内部的变量定义

  • 如果需要在case的流程中定义变量需要加上块来确保定义域,不然会报错,c++中不允许跨过变量的初始化语句去直接使用这个变量

5.3.2节练习

alt

  • 练习5.9:
using namespace std;
#include<iostream>

int main()
{
	string text;
	int num = 0;
	while (cin >> text)
	{
		for (auto temp: text) {
			if (temp == 'a') {
				num++;
			}
			else if (temp == 'e') {
				num++;
			}
			else if (temp == 'i') {
				num++;
			}
			else if (temp == 'o') {
				num++;
			}
			else if (temp == 'u') {
				num++;
			}
		}
	}
	cout << num << endl;

	system("pause");
	return 0;
}
  • 练习5.10:
using namespace std;
#include<iostream>

int main()
{
	char ch = getVal();
	unsigned vowelCnt = 0;
	switch (ch)
	{
	case 'A': case 'a': case 'B': case 'b': case 'C': case 'c': case 'D': case 'd': case 'E': case 'e':
		++vowelCnt;
	default:
		break;
	}
	cout << num << endl;

	system("pause");
	return 0;
}
  • 练习5.11:
using namespace std;
#include<iostream>

int main()
{
	char ch = ' ';
	unsigned vowelCnt = 0;
	unsigned block = 0;
	switch (ch)
	{
	case 'A': case 'a': case 'B': case 'b': case 'C': case 'c': case 'D': case 'd': case 'E': case 'e':
		++vowelCnt;
		break;
	case '\n': case ' ' : case '\t':
		++block;
		break;
	default:
		break;
	}
	cout << block << endl;

	system("pause");
	return 0;
}

  • 练习5.12:
using namespace std;
#include<iostream>

int main()
{
	string ch = "flflfffi";
	int num = 0;
	for (int i = 0; i < ch.size(); i++)
	{
		if ((ch[i] == 'f') && (i + 1 < ch.size())) {
			switch (ch[i+1])
			{
			case 'l': case 'i':
				++num;
				break;
			case 'f':
				++num;
				++i;
				break;
			default:
				break;
			}
		}
	}

	cout << num << endl;

	system("pause");
	return 0;
}
  • 练习5.13
    (a):a、e的case语句中没加break
    (b):ix在在default中未定义 (c):多个case使用:连接 (d):case必须使用常量表达式而非变量 ###5.4.1节练习 alt
using namespace std;
#include<iostream>
#include<vector>


int main()
{
	string str;
	string temp = " ";
	int temp_times = 1;
	vector<string> ret_str;
	vector<int> ret_times;
	while (cin >> str)
	{
		if ((temp != " ") && (temp != str))
		{
			ret_times.push_back(temp_times);
			temp_times = 1;
		}
		if ((temp_times == 1) && (str != temp))
		{
			ret_str.push_back(str);
		}
		if (str == temp)
		{
			++temp_times;
		};

		temp = str;
		cout << temp_times << endl;
	}
	ret_times.push_back(temp_times);


	int temp_max = 0;
	string temp_max_str = " ";
	for (int i = 0; i < ret_times.size(); ++i)
	{
		if (ret_times[i] > temp_max)
		{
			temp_max = ret_times[i];
			temp_max_str = ret_str[i];
		}
		else if (ret_times[i] = temp_max)
		{
			temp_max_str = temp_max_str + "、" + ret_str[i];
		}
	}
	if (temp_max == 1)
	{
		cout << "没有单词重复出现过" << endl;
	}
	else
	{
		cout << temp_max_str << ": 出现" << temp_max << "次" << endl;
	}

	system("pause");
	return 0;
}

传统for语句

  • for语句可以定义多个语句头,但是必须定义的数据类型必须一致如: for (int i = 0, j = 0; i < 10, j++){......}
  • for语句可以完全省略语句部分,如下: for (;;){break}

5.4.2节练习

alt (a)

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

int main()
{
	for (int ix = 0; ix != sz; ++ix)
	{
		if (ix != se){...}
	}
	system("pause");
	return 0;
}

(b)

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

int main()
{
	int ix;
	for (; ix != sz; ++ix){......}

	system("pause");
	return 0;
}

(c):要么不循环、要么死循环,明确一下sz的值即可

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


int main()
{
	int sz = 1;
	for (int ix = 0; ix != sz; ++ix) {......}
	system("pause");
	return 0;
}

  • 练习5.16:省略
  • 练习5.17:
using namespace std;
#include<iostream>
#include<vector>

bool compare_vec(vector<int>* p1, vector<int>* p2)
{
	vector<int>::iterator iter1 = (*p1).begin();
	vector<int>::iterator iter2 = (*p2).begin();
	for (; iter2 < (*p2).end(); ++iter2)
	{
		if ((iter1 != p1->end()) && (*iter2 == *iter1))
		{
			++iter1;
		}
	}
	if (iter1 == (*p1).end())
	{
		return true;
	}
	else
	{
		return false;
	}
}


int main()
{
	vector<int> vec1 = { 1, 2, 3, 4 };
	vector<int> vec2 = { 1, 2, 3, 4, 5, 6, 7, 8};
	vector<int>* p1 = (vec1.size() < vec2.size() ? &vec1 : &vec2);
	vector<int>* p2 = (vec1.size() > vec2.size() ? &vec1 : &vec2);
	bool ret = compare_vec(p1, p2);
	cout << ret << endl;
	system("pause");
	return 0;
}

do while语句

  • 条件部分不允许定义变量
  • 循环条件的变量不能定义在do代码块内

5.4.4节练习

alt (a):循环执行的代码没有用块包裹
(b):条件不符不允许定义变量
(c):循环条件的变量不能定义在do代码块内

  • 练习5.19:
using namespace std;
#include<iostream>

int main()
{
	do
	{
		cout << "请输入两个字符串" << endl;
		string s1, s2;
		cin >> s1 >> s2;
		cout << (s1.length() > s2.length() ? s2 : s1) << endl;
	} while (cin);
	system("pause");
	return 0;
}

5.5.1节练习

alt

using namespace std;
#include<iostream>

int main()
{
	string str;
	string temp = "";
	while (cin >> str)
	{
		if (str == temp)
		{
			break;
		}
		temp = str;
	}
	system("pause");
	return 0;
}

continue语句

  • switch语句只有嵌套在迭代语句中时才能在switch中使用continue

5.5.2节练习

alt

using namespace std;
#include<iostream>

int main()
{
	string str;
	string temp = "";
	while (cin >> str)
	{
		temp[0] = char(temp[0] - 32);
		if (str == temp)
		{
			break;
		}
		temp = str;
	}
	system("pause");
	return 0;
}

goto语句

  • 标识符+:,可以作为goto的跳跃目标如:example:,并且与标识符可以与其它实体同名
using namespace std;
#include<iostream>

int main()
{
	goto example;
	cout << 1 << endl;
	example: cout << 2 << endl;

	int a = 10;
	goto a;
	cout << 3 << endl;
	a:
	system("pause");
	return 0;
}
  • goto先后跳跃过已执行的定义语句是合法,该定义语句会被销毁,然后重新执行初始化操作
  • goto语句不能跳跃过变量定义,goto跳跃的标签名需要和goto在同一函数内

5.5.3节练习

alt

  • 练习5.22:
using namespace std;
#include<iostream>

int get_size()
{
	return 1;
}

int main()
{
	
	while (1)
	{
		int sz = get_size();
		if (sz > 0)
			break;
	}
	system("pause");
	return 0;
}

###try语句块和异常处理

  • try->throw异常->catch异常->处理异常

5.6.3节练习

  • 练习5.23:
using namespace std;
#include<iostream>

int main()
{
	int int1, int2;
	cin >> int1 >> int2;
	cout << int1 / int2 << endl;

	system("pause");
	return 0;
}

  • 练习5.24:
using namespace std;
#include<iostream>

int main()
{
	int int1, int2;
	cin >> int1 >> int2;
	if (int2 == 0)
	{
		throw runtime_error("zero");
	}
		
	cout << int1 / int2 << endl;

	system("pause");
	return 0;
}
  • 练习5.25:
using namespace std;
#include<iostream>
#include<stdexcept>

int main()
{
	int int1;
	int int2;
	int ret;
	while (cin >> int1 >> int2)
	{
		try {
			if (!int2)
				throw exception("zero");
			ret = int1 / int2;
		}catch (exception err){
			cout << err.what()
				<< "请再次尝试" << endl;
			char ch;
			cin >> ch;
			if (!cin || ch == 'n')
			{
				break;
			}
		}
	}
	system("pause");
	return 0;
}

C++Prime学习笔记 文章被收录于专栏

勇敢和愚蠢只有一剑之差

全部评论

相关推荐

头像
02-15 16:23
中南大学 Java
野猪不是猪🐗:签了美团真是不一样! 亲戚们都知道我签了美团,过年都围着我问送一单多少钱,还让弟弟妹妹们引以为戒,笑我爸我妈养了个🐢孩子,说从小就知道我这个人以后肯定没出息,我被骂的都快上天了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务