7-2 圆形体体积计算器 (15 分)
本题要求实现一个常用圆形体体积的计算器。计算公式如下:
球体体积 V=
3
4
πr
3
,其中r是球体半径。
圆柱体体积 V=πr
2
h,其中r是底圆半径,h是高。
圆锥体体积 V=
3
1
πr
2
h,其中r是底圆半径,h是高。
输入格式:
在每次计算之前,要求输出如下界面:
1-Ball
2-Cylinder
3-Cone
other-Exit
Please enter your command:
然后从标准输入读进一个整数指令。
输出格式:
如果读入的指令是1或2或3,则执行相应的体积计算;如果是其他整数,则程序结束运行。
当输入为1时,在计算球体体积之前,打印Please enter the radius:,然后读入球体半径,完成计算;
当输入为2时,在计算圆柱体体积之前,打印Please enter the radius and the height:,然后读入底圆半径和高,完成计算;
当输入为3时,在计算圆锥体体积之前,打印Please enter the radius and the height:,然后读入底圆半径和高,完成计算。
计算结果在一行内输出,保留小数点后两位。
输入样例:
1
2
3
2.4 3
0
输出样例:
1-Ball
2-Cylinder
3-Cone
other-Exit
Please enter your command:
Please enter the radius:
33.51
1-Ball
2-Cylinder
3-Cone
other-Exit
Please enter your command:
Please enter the radius and the height:
18.10
1-Ball
2-Cylinder
3-Cone
other-Exit
Please enter your command:
#include<stdio.h>
#define PI 3.1415926535
void Ball()
{
double r;
scanf("%lf",&r);
printf("%.2lf\n",(4.0/3.0)*PI*r*r*r);
}
void Cylinder()
{
double r,h;
scanf("%lf %lf",&r,&h);
printf("%.2lf\n",PI*r*r*h);
}
void Cone()
{
double r,h;
scanf("%lf %lf",&r,&h);
printf("%.2lf\n",(1.0/3.0)*PI*r*r*h);
}
int main(void)
{
int command;
while(1)
{
printf("1-Ball\n2-Cylinder\n3-Cone\nother-Exit\n");
printf("Please enter your command:\n");
scanf("%d",&command);
if((command!=1)&&(command!=2)&&(command!=3))
{
// printf("other-Exit\nPlease enter your command:\n");
break;
}
switch(command)
{
case 1: printf("Please enter the radius:\n");Ball(); break;
case 2: printf("Please enter the radius and the height:\n");Cylinder(); break;
case 3: printf("Please enter the radius and the height:\n"); Cone(); break;
}
}
}
7-3 近似求PI (15 分)
本题要求编写程序,根据下式求π的近似值,直到最后一项小于给定精度eps。
2
π
=1+
3
1!
+
3×5
2!
+
3×5×7
3!
+⋯+
3×5×⋯×(2×i+1)
i!
+⋯
输入格式:
输入在一行中给出精度eps,可以使用以下语句来读输入:
scanf("%le", &eps);
输出格式:
在一行内,按照以下格式输出π的近似值(保留小数点后5位):
PI = 近似值
输入样例:
1E-5
输出样例:
PI = 3.14158
#include<stdio.h>
double fac(double n);
double mul(double n);
int main(void)
{
double eps;
double x=1;
double i,j=2;
scanf("%le",&eps);
if(eps>=1e-1)
printf("PI = %.5lf",2*x);
else
{
for(i=1;fac(i)*1.0/mul(j)>eps;i++)
{
x+=(fac(i)*1.0/mul(j));
j++;
}
x+=(fac(i)*1.0/mul(j));
printf("PI = %.5lf",2.0*x);
}
}
double fac(double n)
{
double f;
if(n==0) return 1;
f=fac(n-1)*n;
return f;
}
double mul(double n)
{
double s;
if(n==1) return 1;
s=mul(n-1)*(2*n-1);
return s;
}
//1e-5
7-4 验证“哥德巴赫猜想” (20 分)
数学领域著名的“哥德巴赫猜想”的大致意思是:任何一个大于2的偶数总能表示为两个素数之和。比如:24=5+19,其中5和19都是素数。本实验的任务是设计一个程序,验证20亿以内的偶数都可以分解成两个素数之和。
输入格式:
输入在一行中给出一个(2, 2 000 000 000]范围内的偶数N。
输出格式:
在一行中按照格式“N = p + q”输出N的素数分解,其中p ≤ q均为素数。又因为这样的分解不唯一(例如24还可以分解为7+17),要求必须输出所有解中p最小的解。
输入样例:
24
输出样例:
24 = 5 + 19
}
#include<stdio.h>
#include<math.h>
int prime(int n)
{
int i;
if(n<=1) return 0;
else if(n==2) return 1;
else if(n%2==0) return 0;
else
{
for(i=2;i<=sqrt(n);i++)
if(n%i==0)
return 0;
return 1;
}
}
int main(void)
{
int n,i;
int l,m;
scanf("%d",&n);
for(i=2;i<n/2;i++)
if(prime(i))
if(prime(n-i))
break;
printf("%d = %d + %d\n",n,i,n-i);
}