《C++程序设计原理与实践》部分习题答案 1

首先要声明,本人也是刚刚开始自学C++,用的书就是这本《C++程序设计原理与实践》,课后习题 都是自学完本章之后选做的。编程能力渣得拿不出手,如果有错误还请不吝赐教~另外,本人的时间管理有比较大的问题,所以不定期更新。


2.1

#include <iostream>
using namespace std;         //cout和cin是定义在std命名空间内的对象
int main()
{
	cout<<"Hello,programming!\n";
	cout<<"Here we go!\n";
	getchar();
	return 0;
}
如果不使用getchar(),则会立刻退出程序,看不到程序结果。


3.2

#include <iostream>

using namespace std;

int main()
{
	cout<<"Please input a mil\n";
	double mil;
	cin>>mil;
	double km;
	km=mil*1.609;
	cout<<"It is equal "<<km<<" km\n";
	system("pause");
	return 0;
}


3.6

#include <iostream>

using namespace std;

int main()
{
	cout<<"please input three int value\n";
	int x,y,z,i;
	cin>>x>>y>>z;
	if(x>y)
	{
		i=x;
		x=y;
		y=i;
	}
	if(y>z)
	{
		i=y;
        y=z;
		z=i;
	}
	if(x>y)
	{
		i=x;
		x=y;
		y=i;
	}
	cout<<x<<","<<y<<","<<z<<"\n";
	system("pause");
}


3.7

#include <iostream>
#include <string>

using namespace std;

int main()
{
	cout<<"please input three string\n";
	string x,y,z,i;
	cin>>x>>y>>z;
	if(x>y)
	{
		i=x;
		x=y;
		y=i;
	}
	if(y>z)
	{
		i=y;
        y=z;
		z=i;
	}
	if(x>y)
	{
		i=x;
		x=y;
		y=i;
	}
	cout<<x<<","<<y<<","<<z<<"\n";
	system("pause");
}


4.6

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

int main()
{
	string str;
	int n,i,k;
	char c;
	k=1;
	vector<string> v;
	v.push_back("zero");
	v.push_back("one");
	v.push_back("two");
	v.push_back("three");
	v.push_back("four");
	v.push_back("five");
	v.push_back("six");
	v.push_back("seven");
	v.push_back("eight");
	v.push_back("nine");
	while(1)
	{
	cout<<"数字转换拼写请输入y;拼写转换数字请输入n,退出请输入q\n";
	cin>>c;
	switch(c)
	{
	case 'q':goto loop;
	case 'y':
		cout<<"请输入需要转换的数字\n";
		cin>>n;
		if (n>=0&&n<=9) cout<<"转换的拼写为:"<<v[n]<<endl;
		else cout<<"输入的数有误!"<<endl;
		break;
	case 'n':
		cout<<"请输入需要转换的拼写\n";
		cin>>str;
		for(i=0;i<=9;i++)
		{
			if(str==v[i]) 
			{
				cout<<"转换的数字为:"<<i<<endl;
				k=0;
			}
		}
		if (k==1)
		{
			cout<<"输入的拼写有误!"<<endl;
			k=0;
		}
		break;
	default:cout<<"请输入正确的命令!\n";
	}
	}
	loop:system("pause");
}


4.19

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

int main()
{
	int i=0;
	int n;
	string name;
	int score;
	vector<string> names;
	vector<int> scores;
	while(1)
	{
		cout<<"请输入名字和分数:\n";
		cin>>name;
		names.push_back(name);
		if(cin>>score)
		{
			scores.push_back(score);
			i++;
		}
		else if(name!="no") 
		{
			cin.clear();    //这里如果用cin.clear(istream::failbit); 是不行的
			cin.ignore(numeric_limits<streamsize>::max(),'\n');       //清空输入缓存区!!!
			cout<<"请输入正确的分数!\n";


			cin>>score;
			scores.push_back(score);
			i++;
		}
		else goto loop;
		for(n=0;n<i-1;n++)
		{
			if(names[i-1]==names[n]) 
			{
				cout<<"输入名字已存在!数据无效\n";
				names.pop_back();
				scores.pop_back();         //删除最后的数据
				i--;
			}
		}
	}
loop:for(n=0;n<i;n++)
	 {
		cout<<names[n]<<"  "<<scores[n]<<endl;
	 }
	system("pause");
}


已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页