课后练习5.14
课后练习 5.17
#include<iostream>
#include<string>
using namespace std;
#include <vector>
int main()
{
vector<int> val1 = { 0, 1, 3, 4, 5, 6 };
vector <int> val2 = { 0,1, 3, 4, 5, 6, 8 };
int cnt = 0;
int small_size = val1.size() > val2.size() ? val2.size() : val1.size();
for (decltype(val1.size()) i = 0; i != small_size; ++i)
{
if (val1[i] != val2[i])
{
cout << "false" << endl;
cnt++;
}
}
if (cnt == 0)
{
cout << "true" << endl;
}
cin.get();
}
习题5.19
#include<iostream>
#include<string>
using namespace std;
#include <vector>
int main()
{
cout << "请输入两个字符串,用空格隔开" << endl;
string My_string1;
string My_string2;
do
{
cin >> My_string1 >> My_string2;
if (My_string1.size() > My_string2.size())
{
cout << "短的为: " << My_string2 << endl;
}
else if (My_string1.size() < My_string2.size())
{
cout << "短的为: " << My_string1 << endl;
}
else
{
cout << My_string1 << "和" << My_string2 << "一样长" << endl;
}
} while (cin );
cin.get();
}
习题 5.20
#include<iostream>
#include<string>
using namespace std;
#include <vector>
int main()
{
cout << "请输入一个单词,输入stop表示结束" << endl;
string My_string1, before_string;
string Stopword = "stop"; // 用来表示停止读入
int cnt = 0; //用来跳出循环
cin >> My_string1;
while (cnt == 0)
{
before_string = My_string1;
if (My_string1 == Stopword)
{
if (My_string1 != before_string)
{
cout << "没有重复单词" << endl;
++cnt;
break;
}
cout << "没有重复单词" << endl; //保证 如果第一次输入的是stop 则直接输出 没有重复
break;
}
else
{
cout << "继续输入另一个单词" << endl;
cin >> My_string1;
if (My_string1 == before_string)
{
cout << "重复的单词是 : " << before_string << endl;
++cnt;
break;
}
else
{
before_string = My_string1;
}
}
}
cin.get();
}
5.23
#include<iostream>
#include<string>
using namespace std;
#include <vector>
#include <stdexcept>
int main()
{
int a, b;
cout << "请输入被除数与除数a 和 b" << endl;
while (cin >> a >> b)
{
try{
if (b == 0)
{
throw std::runtime_error("除数不能为0");
}else
cout << static_cast<double> (a) / b << endl;
cout << "是否继续输入? enter y or n" << endl;
char d;
cin >> d;
if (!cin || d == 'n')
{
break;
}
}
catch (runtime_error err) {
cout << err.what() << endl;
cout << "是否需要重新输入? enter y or n: " << endl;
char c;
cin >> c;
if (!cin || c == 'n')
{
break;
}
}
}
cin.get();
}