如何使C程序循环回到启动功能?

时间:2018-11-22 14:34:52

标签: c

例如,对于该计算等级3的方程式的程序,在计算出该方程式之后,它将停止。我该如何做,使其再次循环回到开始而无需再次执行?我仍然对这个平台还不熟悉,所以请您照顾!

#include < stdio.h >

int main() {
  int a, v, b, c, delt;
  float x1, x2;

  printf("\nIntroduceti cele 3 parametrii ecuatia: ");

  scanf("%d %d %d", & a, & b, & c);
  if (a != 0) {
    v = pow(b, 2);
    delt = v - (4 * a * c);

    if (delt >= 0) {

      delt = sqrt(delt);
      x1 = -(b + delt) / (2.0 * a);
      x2 = -(b - delt) / (2.0 * a);

      printf("\nValoara lui x1 este: %f", x1);
      printf("\n");
      printf("\nValoara lui x2 este: %f", x2);

    } else {
      printf("Ecuatia nu are soluti! \n");
    }

  } else if (a == 0) {
    printf("\nBLACKHOLE");
  }

  return 0;
}

2 个答案:

答案 0 :(得分:1)

您可以将所有内容包装在do-while循环中,并询问用户是否要继续执行,例如:

int a,v,b,c,delt;
float x1,x2;
char choice;
do{
    printf("\nIntroduceti cele 3 parametrii ecuatia: ");
    scanf("%d %d %d", &a, &b, &c);
    if(a!=0)
    {
        v=pow(b, 2);
        delt = v-(4*a*c);

        if (delt>=0)
        {
            delt=sqrt(delt);
            x1=-(b+delt)/(2.0*a);
            x2=-(b-delt)/(2.0*a);

            printf("\nValoara lui x1 este: %f", x1);
            printf("\n");
            printf("\nValoara lui x2 este: %f", x2);
        }
        else
        {
            printf("Ecuatia nu are soluti! \n");
        }
    }
    else if(a==0)
    {
        printf("\nBLACKHOLE");
    }
    printf("\nEvaluate new equation?(y/n) ")
    scanf("%c",&choice)
}while(strcmp(choice,"y")==0);

return 0;

do{...}内的块将至少执行一次,然后将要求用户输入一个字符(y / n)来决定是否继续。 strcmp(string1,string2)比较两个字符串,如果相等则返回0,因此,如果用户选择“ y”,则strcmp将返回0,并且do-while将再次执行。

答案 1 :(得分:0)

只需将代码包装成无限循环(while(1) { /* Your code here*/ }):

#include < stdio.h >

int main() {
  int a, v, b, c, delt;
  float x1, x2;

  while (1) {
    printf("\nIntroduceti cele 3 parametrii ecuatia: ");

    scanf("%d %d %d", & a, & b, & c);
    if (a != 0) {
      v = pow(b, 2);
      delt = v - (4 * a * c);

      if (delt >= 0) {

        delt = sqrt(delt);
        x1 = -(b + delt) / (2.0 * a);
        x2 = -(b - delt) / (2.0 * a);

        printf("\nValoara lui x1 este: %f", x1);
        printf("\n");
        printf("\nValoara lui x2 este: %f", x2);

      } else {
        printf("Ecuatia nu are soluti! \n");
      }

    } else if (a == 0) {
      printf("\nBLACKHOLE");
    }
  }

  return 0;
}