南大C++:《程序设计教程 用C++语言编写》答案(四)
这些是我自己写的代码,全部通过编译。
4.9.13 编程解决下面的问题:若一头小母牛,从出生第四个年头开始每年生一头母牛,按此规律,第n年有多少头母牛?
/*
P106 4.9.13
编程解决下面的问题:若一头小母牛,从出生第四个年头开始每年生一头母牛,按此规律,第n年有多少头母牛?
*/
#include <iostream>
using namespace std;
int cow(int n)
{
if (n <= 3)
return 1;
else
return cow(n-1) + cow(n - 3);
}
int main()
{
int n;
for (int i = 1; i <= 20; i++)
{
cout << "第" << i << "年:" << cow(i) << endl;
}
}
5.8.4 从键盘输入某个星期每一天的最高和最低温度,然后计算该星期的平均最低和平均最高温度并输出。
/*
P165 5.8.4
从键盘输入某个星期每一天的最高和最低温度,然后计算该星期的平均最低和平均最高温度并输出。
*/
#include <iostream>
using namespace std;
int main()
{
int min, max,t;
min = max = 0;
for (int i = 1; i <= 7; i++)
{
cout << "第" << i << "天:"<<endl;
cout << "最高:";
cin >> t;
max += t;
cout << "最低:";
cin >> t;
min += t;
}
cout << "平均最高:" << max / 7 << " 平均最低:" << min / 7 << endl;
}
5.8.5 编写一个函数,判断其int型参数值是否是回文数。回文数是指从正向和反向两个方向读数字都一样,例如,9783879就是一个回文数。
/*
P165 5.8.5
编写一个函数,判断其int型参数值是否是回文数。回文数是指从正向和反向两个方向读数字都一样,例如,9783879就是一个回文数。
*/
#include <iostream>
using namespace std;
bool h(int n)
{
int t = n;
int p=0;
while (t)
{
p = p * 10 + t % 10;
t = t / 10;
}
if (p == n)
return true;
else
return false;
}
int main()
{
int n;
while (1)
{
cout << "n:";
cin >> n;
cout << "是否为回文数:" << h(n) << endl;
}
}
5.8.6 编写一个函数,把一个int型数(由参数n表示)转换成一个字符串(放在str中)。
/*
P165 5.8.6
编写一个函数,把一个int型数(由参数n表示)转换成一个字符串(放在str中)。
*/
#include <iostream>
using namespace std;
void int_to_str(int &n, char str[],int &l)
{
int t;
if (n != 0)
{
t = n % 10;
n = n / 10;
int_to_str(n , str, l);
}
else
{
l = -1;
return;
}
++l;
str[l] = t+'0';
}
int main()
{
int n,l;
char s[100];
while (1)
{
cout << "n:";
cin >> n;
int_to_str(n, s, l);
s[l + 1] = '\0';
cout << "string:" << s << endl;
}
}
5.8.7 编写一个函数计算一元二次方程的根。要求方程的系数和根均用参数传递机制来传递。函数返回0表示没有根,返回1表示同根,返回2表示2个根。
/*
P165 5.8.7
编写一个函数计算一元二次方程的根。要求方程的系数和根均用参数传递机制来传递。函数返回0表示没有根,返回1表示同根,返回2表示2个根。
*/
#include <iostream>
using namespace std;
int j(int a, int b, int c)
{
int t = b*b - 4 * a*c;
if (t < 0)
return 0;
else if (t == 0)
return 1;
else
return 2;
}
int main()
{
int a, b, c;
while (1)
{
cout << "一元二次方程系数:" << endl;
cout << "a:";
cin >> a;
cout << "b:";
cin >> b;
cout << "c:";
cin >> c;
cout << "返回值:" << j(a, b, c) << endl;
}
}