示例 1:使用 if 语句
#include <stdio.h>
int main() {
double n1, n2, n3;
printf("Enter three different numbers: ");
scanf("%lf %lf %lf", &n1, &n2, &n3);
// if n1 is greater than both n2 and n3, n1 is the largest
if (n1 >= n2 && n1 >= n3)
printf("%.2f is the largest number.", n1);
// if n2 is greater than both n1 and n3, n2 is the largest
if (n2 >= n1 && n2 >= n3)
printf("%.2f is the largest number.", n2);
// if n3 is greater than both n1 and n2, n3 is the largest
if (n3 >= n1 && n3 >= n2)
printf("%.2f is the largest number.", n3);
return 0;
}
在这里,我们使用了 3 条不同的 if
语句。第一条检查 n1 是否是最大的数字。
第二条和第三条 if
语句分别检查 n2 和 n3 是否是最大的。
这个程序最大的缺点是,无论哪个数字最大,所有 3 个 if
语句都会被执行。
然而,我们只想执行一个 if
语句。我们可以通过使用 if...else
阶梯来实现这一点。
示例 2:使用 if...else 阶梯
#include <stdio.h>
int main() {
double n1, n2, n3;
printf("Enter three numbers: ");
scanf("%lf %lf %lf", &n1, &n2, &n3);
// if n1 is greater than both n2 and n3, n1 is the largest
if (n1 >= n2 && n1 >= n3)
printf("%.2lf is the largest number.", n1);
// if n2 is greater than both n1 and n3, n2 is the largest
else if (n2 >= n1 && n2 >= n3)
printf("%.2lf is the largest number.", n2);
// if both above conditions are false, n3 is the largest
else
printf("%.2lf is the largest number.", n3);
return 0;
}
在此程序中,当 n1 是最大的时,只有 if
语句会被执行。
同样,当 n2 是最大的时,只有 else if
语句会被执行,依此类推。
示例 3:使用嵌套的 if...else
#include <stdio.h>
int main() {
double n1, n2, n3;
printf("Enter three numbers: ");
scanf("%lf %lf %lf", &n1, &n2, &n3);
// outer if statement
if (n1 >= n2) {
// inner if...else
if (n1 >= n3)
printf("%.2lf is the largest number.", n1);
else
printf("%.2lf is the largest number.", n3);
}
// outer else statement
else {
// inner if...else
if (n2 >= n3)
printf("%.2lf is the largest number.", n2);
else
printf("%.2lf is the largest number.", n3);
}
return 0;
}
在此程序中,我们使用了嵌套的 if...else
语句来找到最大的数字。让我们更详细地看看它们是如何工作的。
1. 外部 if 语句
首先,注意外部的 if
语句以及其中包含的内部 if...else 语句。
// outer if statement
if (n1 >= n2) {
// inner if...else
if (n1 >= n3)
printf("%.2lf is the largest number.", n1);
else
printf("%.2lf is the largest number.", n3);
}
在这里,我们正在检查 n1 是否大于或等于 n2。如果是,程序控制会转到内部的 if...else
语句。
内部的 if
语句检查 n1 是否也大于或等于 n3。
如果是,那么 n1 要么等于 n2 和 n3,要么现在它大于 n2 和 n3,即 n1 >= n2 >= n3
。因此,n1 是最大的数字。
否则,n1 大于或等于 n2,但小于 n3,即 n3 > n1 >= n2
。因此,n3 是最大的数字。
2. 外部 else 语句
当 n2 > n1
时,将执行外部 else
语句。
// outer else statement
else {
// inner if...else
if (n2 >= n3)
printf("%.2lf is the largest number.", n2);
else
printf("%.2lf is the largest number.", n3);
}
此部分程序的内部 if...else
使用与之前相同的逻辑。唯一的区别是,我们正在检查 n2 是否大于 n3。
上面所有这些程序的输出都将是相同的。
Enter three numbers: -4.5 3.9 5.6 5.60 is the largest number.