【学习ios之路:C语言】If循环的应用的练习题
【学习ios之路:C语言】If循环的应用的练习
1.求三个数中的最大值
<span style="font-size:14px;"></span><pre name="code" class="cpp"><span style="font-size:14px;"> //方法1:先找到两个数的最大值,然后用最大值和第三个进行比较.</span>
int n1 = 0, n2 = 0 ,n3 = 0 ;
printf("请输入三个数:\n");
scanf("%d%d%d", &n1, &n2, &n3);
int max = 0;//定义一个最大值,初始值为0
if (n1 > n2) {
max = n1;
} else {
max = n2;
} //用条件表达式替换 为 max = n1 > n2 ? n1 : n2;
if (max < n3) {
max = n3;
}// max = max > n3 ? max : n3;
printf("最大值为:max = %d", max);
//方法2:用n1分别和 n2 ,n3 比较.
<pre name="code" class="cpp"><pre name="code" class="cpp"> int n1 = 0, n2 = 0 ,n3 = 0 ;
printf("请输入三个数:\n");
scanf("%d%d%d", &n1, &n2, &n3);
int max = 0 ;
if (n1 >n2) {
if (n1 > n3) {
max = n1;
} else {
max = n3;
}
} else if ( n2 > n3) {
max = n2;
} else {
max = n3;
}//相当于 max = n1 > n2 ? n1 > n3 ? n1 : n3 : n2 ? n3 : n2 : n3
printf("最大值为:max = %d", max);
2.输入三个数,用两种方法打印出中间值(即第二大值)
提示:第一种,先求最大最小;第二种,只使用条件运算符
//方法1
float x = 0.0;
float y = 0.0;
float z = 0.0;
float max = 0.0;//定义最大值
float min = 0.0;//定义最小值
float mid = 0.0;//定义中间值
printf("please input three number:\n");
scanf("%f%f%f", &x, &y, &z);
max = x > y ? x > z ? x : z : y > z ? y : z;
min = x < y ? x < z ? x: z : y < z ? y : z;
mid = x + y + z - min - max;
printf("the mid number is: %.2f\n", mid);
//方法2
float x = 0.0;
float y = 0.0;
float z = 0.0;
float max = 0.0;//定义最大值
float min = 0.0;//定义最小值
float mid = 0.0;//定义中间值
printf("please input three number:\n");
scanf("%f%f%f", &x, &y, &z);
if (x >= y) {
if (y >= z ) {
mid = y;
} else {
if (x <= z) {
mid = x;
} else {
mid = z;
}
}
} else {
if (y <= z) {
mid = y;
} else if (x > z) {
mid = y;
} else {
mid = x;
}
}
printf("the mid number is: %.2f\n", mid);