一.用if语句构造多分支结构
#include <stdio.h>
#include <math.h>
int main()
{
float x, y;
scanf_s("%f", &x);
if (x < 2)
{
y = x;
}
else if (x < 6)
{
y = x * x + 1;
}
else if (x < 10)
{
y = sqrt(x + 1);
}
else
{
y = 1 / (x + 1);
}
printf("%f\n", y);
}
二.if语句的嵌套
1.if语句嵌套就是if语句中包含一个或多个if语句。
2.else总是与它上面最近的,且未配对的if配对。
3.为了避免误用,最好使每一层内嵌的if语句都包含else子句。
4.如果if与else的数目不一样,加花括号来确定配对关系。
#include <stdio.h>
#include <math.h>
int main() {
double a, b, c, x1, x2, delta;
scanf_s("%lf %lf %lf", &a, &b, &c);
delta = b * b - 4 * a * c; //好风格,效率,防止出错,提高可读性,提高可维护性;
if (delta >= 0)
{
if (delta > 0)
{
x1 = (-b + sqrt(delta)) / (2 * a);
x2 = (-b - sqrt(delta)) / (2 * a);
printf("两个不等的实根:x1=%.2f x2=%.2f\n", x1, x2);
}
else
{
x1 = -b / (2 * a