《高级语言程序设计》(C++)
实验5
实验题目:
1、求满足1+5+52+53+54+……+5n <=8000的最大n值。
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int sum = 0;
int ans = 0;
cout << "满足条件的最大n:" << endl;
while (1)
{
sum += pow(5, ans);
if (sum > 8000)
{
cout << ans - 1 << endl;
break;
}
ans++;
}
system("pause");
return 0;
}
2、设计程序,把自己的姓名按如下格式显示在屏幕上。如若姓名为“张三”,则编写程序,在屏幕上显示如下图形:
写出程序代码(注意含三个字的姓名与含两个字的姓名的程序不同),并附以必要的文字说明,将程序的执行结果窗口(图形)复制到实验报告中。
#include <iostream>
using namespace std;
// 8行
int main()
{
string name = "张三";
for (int i = 1; i <= 8; i++)
{
for (int k = 0; k < 8 - i; k++)
{
cout << " ";
}
for (int j = 1; j <= i; j++)
{
cout << name;
}
cout << endl;
}
system("pause");
return 0;
}
3、在主函数中输入圆柱体的高和半径,调用函数求圆柱体积volume并输出。
要求定义和调用函数cylinder (r, h )计算圆柱体的体积。
函数原型为 double cylinder (double r, double h);
#include <iostream>
using namespace std;
const double PI = 3.14;
double cylinder(double r, double h)
{
return (PI * r * r * h);
}
int main()
{
int r, h;
cin >> r >> h;
cout << cylinder(r, h) << endl;
system("pause");
return 0;
}
4、编写sum(int n)函数,求2+4+6+8+……+n,由主函数调用此函数,并输出结果。
#include <iostream>
using namespace std;
int sum(int n)
{
int ans = 0;
for (int i = 2; i <= n; i += 2)
{
ans += i;
}
return ans;
}
int main()
{
int n;
cin >> n;
cout << sum(n) << endl;
system("pause");
return 0;
}
5、在主函数中输入一个数,调用函数判断其奇偶性并输出相应信息。
提示:定义一个判断奇偶数的函数even (n),当n为偶数时返回1,否则返回0。判断奇偶数的函数原型为:int even (int n);
#include <iostream>
using namespace std;
int even(int n)
{
return n % 2 ? 0 : 1;
}
int main()
{
int n;
cin >> n;
cout << even(n);
system("pause");
return 0;
}
6、编写程序,利用函数重载求整数绝对值和实数绝对值。要求在主函数中从键盘上输入求绝对值的数,调用自己编写的函数求出绝对值。
提示:不要使用数学函数,求整数绝对值和实数绝对值的算法是一样的,只是参数的类型不一样。函数原型为:
int f(int);
double f(double);
#include <iostream>
#include <cmath>
using namespace std;
int absolute_num(int num)
{
if (num < 0)
num = -num;
return num;
}
double absolute_num(double num)
{
if (num < 0)
num = -num;
return num;
}
int main()
{
int n;
cin >> n;
cout << absolute_num(n) << endl;
system("pause");
return 0;
}
7、求方程ax2+bx+c=0的根,用三个函数分别求出当b2-4ac大于0,等于0,和小于0时的根,并输出结果。从主函数输入a,b,c的值。
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
void bigger(int a, int b, int c)
{
double x1, x2;
double temp = sqrt(b * b - 4 * a * c);
x1 = ((-1) * b + temp) / (2 * a);
x2 = ((-1) * b - temp) / (2 * a);
cout << "值为:"
<< "x1=" << x1 << " "
<< "x2=" << x2 << endl;
}
void equal(int a, int b)
{
double x;
x = ((-1) * b) / (2 * a);
cout << "值为:"
<< "x=" << x << endl;
}
void smaller(int a, int b, int c)
{
cout << "无解" << endl;
}
int main()
{
int a, b, c;
cout << "输入abc的值:";
cin >> a >> b >> c;
double delta = b * b - 4 * a * c;
if (delta > 0)
{
bigger(a, b, c);
}
else if (delta < 0)
{
smaller(a, b, c);
}
else
{
equal(a, b,c);
}
system("pause");
return 0;
}