C++ primer plus习题集及解析第六章(分支语句和逻辑运算符)

题目:6.1

编写一个程序,读取键盘输入,直到遇到 @符号为止,并回显输入(数字除外),同时将大写字符转换为小写,将小写字符转换为大 写(别忘了cctype函数系列)。

代码: 

void Func()
{
	string ch;
	string ans="";
	cout << "请输入字符(@符号为止):";
	cin >> ch;
	for (int i = 0; i < ch.size(); i++)
	{
		//将数字除去
		if (ch.at(i) == '@')
		{
			break;
		}
		
		if (isalpha(ch.at(i)) != 0)
		{
			ans += ch.at(i);
		}
	}

	//显示输入
	cout << ans << endl;

	//转换大小写
	for (int i = 0; i < ans.size(); i++)
	{
		if (islower(ans.at(i)))
		{
			ans.at(i) = toupper(ans.at(i));
		}
		else 
		{
			ans.at(i) = tolower(ans.at(i));
		}
	}
	cout << ans << endl;

}

题目:6.2

编写一个程序,最多将10个 donation 值读入到一个 double 数组中(如果您愿意,也可使用模板类 array )。程序遇到非数字输入时将结束输入,并报告这些数字的平均值以及数组中有多少个数字大于平均值。 

 代码:

void Func(void)
{
    array<double, 10> donation;
    unsigned int enter = 0;
    double total = 0;
    double avg = 0;
    unsigned int large_avg = 0;

    cout << "请输入有效数字,非数字退出:" << endl;
    while (enter < 10 && (cin >> donation[enter]))
    {
        total += donation[enter];
        enter++;
    }

    avg = total / enter;
    for (unsigned int i = 0; i < enter; i++)
    {
        if (donation[i] > avg)
        {
            large_avg++;
        }
    }

    cout << "平均值为:" << avg << ", 超过平均值的个数为: " << large_avg << endl;
}

题目:6.3

 编写一个菜单驱动程序的雏形。该程序显示一个提供4个选项的菜单——每个选项用一个字母标记。如果用户使用有效选项之外的字母进行响应,程序将提示用户输入一个有效的字母,直到用户这样做为止。然后,该程序使用一条 switch 语句,根据用户的选择执行一个简单操作。该程序的运行情况如下: 

Please enter one of the following choices:

c) carnivore    p) pianist
t) tree         g) game
f

Please enter a c, p, t, or g: q
A maple is a tree.

代码: 

void Func()
{
	cout << "Please enter one of the following choices:" << endl;
	cout << "c) carnivore    p) pianist" << endl;
	cout << "t) tree         g) game" << endl;


	char c;
	bool run = true;
	
	while (run&&cin >> c)
	{
		switch (c)
		{
		case 'c':
			cout << "carnivore" << endl;
			run = false;
			break;
		case 'p':
			cout << "pianist" << endl;
			run = false;
			break;
		case 't':
			cout << "tree" << endl;
			run = false;
			break;
		case 'g':
			cout << "game" << endl;
			run = false;
			break;
		default:
			cout << "Please enter a c, p, t, or g: q" << endl;
			break;
		}
	}

}

 注意:while (run&&cin >> c)和while(cin>>c&&run)在这里是有差别的,第一种先判断run,当发现run是false时,便可直接退出,但是如果cin>>c在前,则此时即便run==false,也不能直接退出,需要先输入。

题目:6.4

加入 Benevolent Order of Programmer 后,在BOP大会上,人们便可以通过加入者的真实姓名、头衔或秘密BOP姓名来了解他(她)。请编写一个程序,可以使用真实姓名、头衔、秘密姓名或成员偏好来列出成员。编写该程序时,请使用下面的结构:

// Benevolent order of programmers strcture

struct bop {
    char fullname[strsize]; // real name
    char title[strsize];    // job title
    char bopname[strsize];  // secret BOP name
    int preference;         // 0 = fullname, 1 = title, 2 = bopname
};

 该程序创建一个有上述结构体组成的小型数组,并将其初始化为适当的值。另外,该程序使用一个循环,让用户在下面的选项中进行选择:

a. display by name     b. display by title
c. display by bopname  d. display by preference
q. quit

 注意,display by preference 并不意味着显示成员的偏好,而是意味着根据成员的偏好来列出成员。例如,如果偏好号为 1,则选择 d 将显示成员的头衔。该程序的运行情况如下:

Benevolent order of Programmers report.

a. display by name     b. display by title
c. display by bopname  d. display by preference
q. quit

Enter your choices: a
Wimp Macho
Raki Rhodes
Celia Laiter
Hoppy Hipman
Pat Hand

Next choice: d   
Wimp Macho
Junior Programmer
MIPS
Analyst Trainee
LOOPY

Next choice: q
Bye!

代码: 

// Benevolent order of programmers strcture
const int strsize = 20;
const int number = 3;//成员数目

struct bop {
    char fullname[strsize]; // real name
    char title[strsize];    // job title
    char bopname[strsize];  // secret BOP name
    int preference;         // 0 = fullname, 1 = title, 2 = bopname
};

void Func( bop*club)
{
    cout << "请选择下列选项:" << endl;
    cout << "a.display by name     b.display by title" << endl;
    cout << "c.display by bopname  d.display by preference" << endl;
    cout << "q.quit" << endl;
    char ch;
    bool run = true;
    while (run && cin >> ch)
    {
        switch (ch)
        {
        case 'a':
            for (int i = 0; i < number; i++)
            {
                cout << club[i].fullname << endl;
            }
            
            break;
        case 'b':
            for (int i = 0; i < number; i++)
            {
                cout << club[i].title << endl;
            }
            break;
        case 'c':
            for (int i = 0; i < number; i++)
            {
                cout << club[i].bopname << endl;
            }
            break;
        case 'd':
            for (int i = 0; i < number; i++)
            {
                if (club[i].preference == 0)
                {
                    cout << club[i].fullname << endl;
                }
                else if (club[i].preference == 1)
                {
                    cout << club[i].title << endl;
                }
                else if (club[i].preference == 2)
                {
                    cout << club[i].bopname << endl;
                }

            }
            break;

        case 'q':
            run = false;
            break;

        default:
            break;
        }
        
    }
    
}

void Init( bop* club)
{
    strcpy_s(club[0].fullname, "fullname1");
    strcpy_s(club[0].bopname, "bopname1");
    strcpy_s(club[0].title, "title1");
    club[0].preference = 1;

    strcpy_s(club[1].fullname, "fullname2");
    strcpy_s(club[1].bopname, "bopname2");
    strcpy_s(club[1].title, "title2");
    club[1].preference = 0;

    strcpy_s(club[2].fullname, "fullname3");
    strcpy_s(club[2].bopname, "bopname3");
    strcpy_s(club[2].title, "title3");
    club[2].preference = 2;

}

int main()
{
    bop club[number];
    Init(club);
    Func(club);

	system("pause");
	return 0;
}

 题目:6.5

 在 Neutronia 王国,货币单位是 tvarp,收入所得税的计算方式如下:

  • 5000 tvarps:不收税;
  • 5001~15000 tvarps:10%;
  • 15001~35000 tvarps:15%;
  • 35000 tvarps以上:20%;

例如,收入为 38000 tvarps 时,所得税为 5000 * 0.00 + 10000 * 0.10 + 20000 * 0.15 + 3000 * 0.20, 即 4600 tvarps。请编写一个程序,使用循环来 要求用户输入收入,并报告所得税。当用户输入负数或非数字时,循环将结束。

代码: 

void Func()
{
	int count = 0;
	 
	cout << "请输入:";
	while (cin >> count && count >= 0)
	{
		int tvarps = 0;
		if (count <= 5000)
		{
			cout << "所收税为:" << tvarps << endl;
		}
		else if (count >= 5001 && count <= 15000)
		{
			tvarps = 5000 * 0 + (count - 5000) * 0.10;
			cout << "所收税为:" << tvarps << endl;
		}
		else if (count >= 15001 && count <= 35000)
		{
			tvarps = 5000 * 0 + 10000 * 0.1 + (count - 15000) * 0.15;
			cout << "所收税为:" << tvarps << endl;
		}
		else if (count > 35000)
		{
			tvarps = 5000 * 0.00 + 10000 * 0.10 + 20000 * 0.15 + (count - 35000) * 0.2;
			cout << "所收税为:" << tvarps << endl;
		}
		cout << "请输入:";
	}


}

题目:6.6

编写一个程序,记录捐助给 “维护合法权利团体” 的资金。该程序要求用户输入捐献者数目,然后要求用户输入每一个捐献者的姓名和款项。这些信息被储存在一个动态分配的结构体数组中。每个结构体有两个成员:用来储存姓名的字符数组(或 string对象)和用来存储款项的 double成员。读取所有的数据后,程序将显示所有捐款超过 10000 的捐款者的姓名及其捐款数额。

该列表前应包含一个标题,指出下面的捐款者是重要捐款人 Grand Patrons。然后,程序将列出其他的捐款者,该列表要以 Patrons 开头。如果某种类别没有捐款者,则程序将打印单词 none。该程序只显示这两种类别,而不进行排序。

代码: 

struct Patrons
{
	string name;
	double money;
};

void Func()
{
	int count = 0;
	cout << "请输入捐献者的数目:";
	cin >> count;
	vector<Patrons*>Grand_Patrons;
	vector<Patrons*>Patron;

	for (int i = 0; i < count; i++)
	{
		Patrons* patron = new Patrons;
		cout << "请输入姓名:";
		cin >> patron->name;
		cout << "请输入捐款金额:";
		cin >> patron->money;

		if (patron->money > 10000)
		{
			Grand_Patrons.push_back(patron);
		}
		else
		{
			Patron.push_back(patron);
		}

	}

	//输出
	cout << "---------------Grand_Patrons-----------------" << endl;
	if (Grand_Patrons.size() == 0)
	{
		cout << "none" << endl;
	}
	else
	{
		vector<Patrons*>::iterator it = Grand_Patrons.begin();
		for (it; it != Grand_Patrons.end(); it++)
		{
			cout << (*it)->name << endl;
		}
	}
	cout << "-------------------Patrons-----------------------" << endl;
	if (Patron.size() == 0)
	{
		cout << "none" << endl;
	}
	else
	{
		vector<Patrons*>::iterator it = Patron.begin();
		for (it; it != Patron.end(); it++)
		{
			cout << (*it)->name << endl;
		}
	}



}

题目:6.7

编写一个程序,它每次读取一个单词,直到用户输入 q。然后,该程序指出有多少个单词以元音打头,有多少个单词以辅音打头,还有多少个单词不属于这两类。为此,方法之一是,使用 isalpha() 来区分以字母和其他字符打头的单词,然后对于通过了 isalpha() 测试的单词,使用 if 或 switch 语句来确定哪些以元音打头。

代码:

void Func()
{
	std::string ch;
	int vowels = 0;
	int consonants = 0;
	int other = 0;
	std::cout << "请输入:";
	
	while (std::cin >> ch && ch != "q")
	{
		if (isalpha(ch[0]))
		{
			//是字母

			switch (toupper( ch[0]))
			{
			case 'A':;
			case 'E':;
			case 'I':;
			case 'O':;
			case 'U':
				++vowels;
				break;

			default:
				++consonants;
				break;
			}
		}
		else
		{
			other++;
		}
		std::cout << "请输入:";
	}
	std:: cout << "vowels=" << vowels << std::endl;
	std::cout << "consonants=" << consonants << std::endl;
	std::cout << "other=" << other << std::endl;


}

题目:6.8

编写一个程序,它打开一个文件文件,逐个字符地读取该文件,直到到达文件末尾,然后指出该文件中包含多少个字符。

代码: 

//C语言方式
void Func()
{

	FILE* file;
	char ch;
	int count = 0;

	fopen_s(&file,"myself.txt", "r"); // 打开文件,以只读方式

	if (file == NULL) {
		printf("无法打开文件\n");
		return ;
	}

	while ((ch = fgetc(file)) != EOF) { // 逐个字符读取文件内容
		count++; // 统计字符数
	}

	fclose(file); // 关闭文件

	printf("文件中的字符数为:%d\n", count);


}
//c++方式实现
void Func()
{
	std::ifstream file("myself.txt");  // 打开文件example.txt
	if (!file) {
		std::cerr << "无法打开文件" << std::endl;
		return ;
	}

	char ch;
	int count = 0;

	while (file.get(ch)) {  // 逐个读取字符直到文件末尾
		count++;
	}

	std::cout << "字符数目:" << count << std::endl;

	file.close();  // 关闭文件

}

 

 

  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值