|
|
检测点10-16
1.在以下代码片段中,scanf函数的返回值可能是 EOF,0,1,2 。
int n, p;
scanf ("%d%d", & n, & p);
2.修改源文件c1010.c,使之除打印每个形状编号、名称和属性外,还打印周长和面积。三角形的面积可以使用海伦公式计算。
参考答案:
# include <stdio.h>
# include <math.h>
# define N 3
enum Shape {Circle, Rectangle, Triangle,};
struct shape_info {
enum Shape type;
union {
float radius;
struct {float height, width;};
struct {float a, b, c;};
} ;
};
void try_again (void)
{
while (getchar () != '\n');
printf ("输入有误,请重新输入:");
}
float hailun (float a, float b, float c)
{
float p = (a + b + c) / 2;
return sqrt (p * (p -a) * (p -b) * (p - c));
}
int main (void)
{
struct shape_info shapes [N];
//以下收集形状资料
for (int i = 0; i < N; i ++)
{
printf ("请选择形状(%d-圆;%d-长方形;%d-三角形):", Circle, Rectangle, Triangle);
int j;
while (scanf ("%d", & j) != 1 || (j != Circle && j != Rectangle && j != Triangle)) try_again ();
shapes .type = (enum Shape) j;
switch (shapes .type)
{
case Circle:
printf ("请输入半径:");
while (scanf ("%f", & shapes .radius) != 1) try_again ();
break;
case Rectangle:
printf ("请输入长和宽:");
while (scanf ("%f%f", & shapes .height, & shapes .width) != 2) try_again ();
break;
case Triangle:
printf ("请输入三个边的长度:");
while (scanf ("%f%f%f", & shapes .a, & shapes .b, & shapes .c) != 3) try_again ();
break;
}
}
//以下打印形状资料
printf ("-----------------------------------------\n");
for (int i = 0; i < N; i ++)
{
printf ("形状%d:", i + 1);
switch (shapes .type)
{
case Circle:
printf ("圆;半径:%.2f;面积:%.2f\n", shapes .radius, 3.14 * shapes .radius * shapes .radius);
break;
case Rectangle:
printf ("长方形;长:%.2f;宽:%.2f;面积:%.2f\n", shapes .height, shapes .width, shapes .height * shapes .width);
break;
case Triangle:
printf ("三角形;边长:%.2f,%.2f,%.2f;面积:%.2f\n", shapes .a, shapes .b, shapes .c, hailun (shapes .a, shapes .b, shapes .c));
break;
}
}
}
|
|