C/C++教程

【c++ | 谭浩翔】第四章练习

本文主要是介绍【c++ | 谭浩翔】第四章练习,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

【c++ | 谭浩翔】第四章练习

【p151 第九题】
在这里插入图片描述

#include <iostream>
using namespace std;

int main()
{
	int y, d, a, b = 0, i;
	int m[11] = { 31,28,31,30,31,30,31,31,30,31,30 };

	cout << "请输入年份:";
	cin >> y;

	cout << "请输入月份:";
	cin >> a;
	while (a > 12 || a < 1)							//判断月份输入是否正确
	{	
		cout << "请输入正确的月份:";
		cin >> a;
	}

	cout << "请输入日:";						
	cin >> d;
	if (a == 2)									//判断日期输入是否正确
	{
		if (y % 4 == 0 && y % 100 != 0)
		{
			m[2] = m[2] + 1;
			while (d > 29 || d < 1)
			{
				cout << "请输入正确的日期:";		
				cin >> d;
			}
		}
		else
		{
			while (d > 29 || d < 1)
			{
				cout << "请输入正确的日期:";
				cin >> d;
			}
		}
	}
	else
	{
		if (a == 1 || a == 3 || a == 5 || a == 7 || a == 8 || a == 10 || a == 12)
		{
			while (d > 31 || d < 1)
			{
				cout << "请输入正确的日期:";
				cin >> d;
			}
		}
		else
		{
			while (d > 30 || d < 1)
			{
				cout << "请输入正确的日期:";
				cin >> d;
			}
		}
	}
		
	for (i = 0; i < a - 1; i++)							//累计月份的天数
	{
		b += m[i];
	}
	d += b;

	cout << "该日是该年的第" << d << "天";

	return 0;
}

【p151 第十题】
在这里插入图片描述

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

int main()
{
	char f[3][80];

	int a = 0, b = 0, c = 0, d = 0, e = 0;

	for (int i = 0; i < 3; i++)
	{
		cout << "请输入第" << i + 1 <<"行文字:";
		cin >> f[i];

		for (int j = 0; j < 80 && f[i][j] != '\10' ; j++)
		{
			if (f[i][j] >= 'A' && f[i][j] <= 'Z')
				a++;
			else if (f[i][j] >= 'a' && f[i][j] <= 'z')
				b ++;
			else if (f[i][j] >= '0' && f[i][j] <= '9')
				c ++;
			else if (f[i][j] == ' ')
				d ++;
			else e++;
		}
	}

	cout << "共有:" << endl;
	cout << "英文大写字母:" << a << "个" << endl;
	cout << "英文小写字母:" << b << "个" << endl;
	cout << "数字:" << c << "个" << endl;
	cout << "空格:" << d << "个" << endl;
	cout << "其它字符:" << e << "个" << endl;

	return 0;
}
}

【P152 第十四题】
在这里插入图片描述

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

int main()
{
	const int n = 5;
	int i, j;
	string str[n], temp;

	cout << "请输入n个字符串,将按字母由小到大排列输出:" << endl;
	for (i = 0; i < n; i++)
		cin >> str[i];

	for (i = 0; i < n - 1; i++)
	{
		for (j = 0; j < n - i - 1; j++)
		{
			if (str[j] > str[j + 1])
			{
				temp = str[j];
				str[j] = str[j + 1];
				str[j + 1] = temp;
			}
		}
			
	}

	cout << endl << "字母由小到大排列输出:" << endl;
	for (i = 0; i < n; i++)
		cout << str[i] << endl;

	return 0;
}

【p152 第十五题】

#include <iostream>
using namespace std;

int main()
{
	int i;
	const int n = 5;
	char str[n][99];

	cout << "请输入需要判断的字符串" << "(共" << n << "个):" << endl;
	for (i = 0; i < n; i++)
	{
		cin >> str[i];
	}

	cout << "以下是以字母A打头的字符串:" << endl;
	for (i = 0; i < n; i++)
	{
		if (str[i][0] == 'A')
			cout << str[i] << endl;
	}

	return 0;
}
这篇关于【c++ | 谭浩翔】第四章练习的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!