引言
今天开始第三章的程序作业题
题目1
题目
使用重载函数编程序分别把两个数和三个数从大到小排列。
作答
这一题的关键在于使用重载函数,那么什么是重载函数呢,在这一题目中也就是函数名一致、形参类型一致但是传递参数的个数不一致的函数。这样我们可以构造两个函数,void paixu(double, double);void paixu(double, double,double);。
函数声明后我们需要实现函数功能了,根据题意第一个函数应该将两个数从大到小排列,使用我们使用if语句判断大小直接输出就可以了。‘
第二个函数涉及到三个参数,我们不妨假设a>b>c,所以我们一一检查这个关系式,当不满足a>b时,我们令a,b互换;当不满足a>c时,我们令a,c互换;当不满足b>c时,我们令b,c互换。检查完成后直接依次输出就可以了。
#include<iostream>
using namespace std;
void paixu(double, double);
void paixu(double, double,double);
int main()
{
double x, y, a, b, c;
cout << "请输入要排序的两个数" << endl;
cin >> x >> y;
cout << "排序结果为:" << endl;
paixu(x, y);
cout << "请输入要排序的三个数" << endl;
cin >> a >> b >> c;
cout << "排序结果为:" << endl;
paixu(a,b,c);
}
void paixu(double x, double y)
{
if (x > y)
cout << x << ' ' << y << endl;
else
cout << y << ' ' << x << endl;
}
void paixu(double a, double b, double c)
{
double temp;
if (a < b)
{
temp = a;
a = b;
b = temp;
}
if (a < c)
{
temp = a;
a = c;
c = temp;
}
if (b < c)
{
temp = b;
b = c;
c = temp;
}
cout << a << ' ' << b << ' ' << c << endl;
}
题目2
题目
猜数游戏。玩家想好了一个1~1000之内的整数,由计算机来猜这个数。如果计算机猜出的数比玩家想的数大,则玩家输入1;如果计算机猜出的数比玩家想的数小,则玩家输入-1;这个过程一直进行到计算机猜中为止,玩家输入0。
作答
这里用到了二分搜索算法的思想,因为这个数一定在1——1000内,所以我们不需要借用数组,只用使用三个变量就可以了。起始时令first==1,last==1000,mid始终为中间数,根据用户输入,我们改变first或last的值,最终就完成了,如果读者对二分搜索算法不了解,可以观看juejin.cn/post/727005…这篇文章。
#include<iostream>
using namespace std;
int main()
{
int first, last, mid;
first = 1;
last = 1000;
mid = (first + last) / 2;
cout << "电脑现在猜这个数是:" << mid << endl;
cout << "(请告诉我,这个数相比你想的那个是大了(1),还是小了(-1),还是就是它(0)" << endl;
int user_num;
cin >> user_num;
while (user_num)
{
while (user_num == 1)
{
last = mid - 1;
mid = (first + last) / 2;
cout << "电脑现在猜这个数是:" << mid << endl;
cout << "(请告诉我,这个数相比你想的那个是大了(1),还是小了(-1),还是就是它(0)" << endl;
cin >> user_num;
}
while (user_num == -1)
{
first = mid + 1;
mid = (first + last) / 2;
cout << "电脑现在猜这个数是:" << mid << endl;
cout << "(请告诉我,这个数相比你想的那个是大了(1),还是小了(-1),还是就是它(0)" << endl;
cin >> user_num;
}
}
cout << "原来这个数是" << mid << "啊!我猜到了,游戏结束!" << endl;
}
总结
这一章到这儿就结束了,感谢阅读!