且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C语言及程序设计初步例程-24 if语句的嵌套

更新时间:2022-10-12 20:38:01

贺老师教学链接  C语言及程序设计初步 本课讲解


应用:分段函数求解
好程序

#include <stdio.h>
int main()
{
    float x, y;
    scanf("%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);
    return 0;
}

//不好的程序
#include <stdio.h>
int main()
{
    float x, y;
    scanf("%f", &x);
    if(x<2)
    {
        y=x;
    }
    if(x>=2&&x<6)
    {
        y=x*x+1;
    }
    if(x>=6&&x<10)
    {
        y=sqrt(x+1);
    }
    if(x>=10) 
    {
        y=1/(x+1);
    }
    printf("%f\n", y);
    return 0;
}

求一元二次方程的根(ax2+bx+c=0)
#include <stdio.h>
int main()
{
  float a,b,c,x1,x2;
  scanf("%f %f %f", &a, &b, &c);
  if ((b*b-4*a*c)>=0)
  {
    if ((b*b-4*a*c)>0)
    {
      x1=(-b+sqrt(b*b-4*a*c))/(2*a);
      x2=(-b-sqrt(b*b-4*a*c))/(2*a);
      printf("两个不等的实根:x1=%.2f x2=%.2f\n", x1, x2);
    }
    else
    {
      x1=-b/(2*a);
      printf("两个相等的实根,x1=x2=%.2f\n", x1);
    }
  }
  else
  {
    printf("方程无实根!\n");
  }
  return 0;
}

求一元二次方程的根——改进后的代码
#include <stdio.h>
int main(){
    float a,b,c,x1,x2,delta;
    scanf("%f %f %f", &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);
            printf("两个相等的实根,x1=x2=%.2f\n", x1);
        }
    }
    else{
        printf("方程无实根!\n");
    }
}