在C中多次运行程序

时间:2014-05-22 07:37:02

标签: c loops

我是编程的新手,所以请原谅我的无知。我在这个网站上没有得到正确答案。这可能是我无法搜索的。 在C中,我编写了一个运行良好的代码。但我想在用户希望的时间内运行代码。这意味着,假设在执行Triangle区域问题后,用户可以反复运行该程序。这需要做什么?这是代码:

#include <stdio.h>
#include <conio.h>
main()
{     

      char a;
      int base, hight, radius, length, width;
      float area, pi=3.14;
      printf("\n\tEnter T to execute the area of Triangle"
      "\n\tEnter R to execute the area of Rectangle"
      "\n\tEnter C to execute the area of Circle\n\t\n\t\n\t\n\t\n\t");
      a=getche();
      printf("\n\t\n\t\n\t\n\t");
      if(a=='T' || a=='t'){
                 printf("You want to know the Area of a Triangle."
                 "\n\tEnter your triangles Base: ");
                 scanf("%d", &base);

                 printf("\n\tEnter your triangles Hight: ");
                 scanf("%d", &hight);

                 printf("\n\tThe base is %d and the hight is %d." 
                 "So the area of your triangle is: \n\n\t\t\t\t", base,hight);

                 area= .5*base*hight;
                 printf("%f", area);
      }

       else if(a=='R' || a=='r'){
                 printf("You want to know the Area of a Rectangle."
                 "\n\tEnter your rectangles Length: ");
                 scanf("%d", &length);

                 printf("\n\tEnter your rectangles Hight: ");
                 scanf("%d", &hight);

                 printf("\n\tThe length is %d and the hight is %d." 
                 "So the area of your Rectangle is: \n\n\t\t\t\t", length,hight);

                 area= length*hight;
                 printf("%f", area);
     }

      else if(a=='C' || a=='c'){
                 printf("You want to know the Area of a Circle."
                 "\n\tEnter your circles Radius: ");
                 scanf("%d", &radius);

                 printf("\n\tThe Radius is %d." 
                 "So the area of your Circle is: \n\n\t\t\t\t", radius);

                 area= pi*radius*radius;
                 printf("%f", area);
      }else{
            printf("Invalid Input");
      }


      getch();

}

1 个答案:

答案 0 :(得分:3)

引入一个布尔变量,比如说repeat。然后设置一个dowhile的无限循环,只要repeat为真,就会重复。在计算之后,询问用户他或她是否愿意继续;可以使用scanf读取结果。然后,相应地设置repeat,这意味着只要repeat变为假,就会终止无限循环。