2014-02-26 39 views
1

我的問題是程序只運行一次... 在這個任務中,我們將開發一個應用程序來計算幾何形狀的面積和周長。首先要求用戶輸入代表形狀爲 的字母。我們用C表示圓,R表示矩形,S表示方形。 用戶選擇形狀後,程序會相應地提示適當的形狀尺寸 。例如,如果用戶選擇了一個正方形,該程序將要求一方。如果它是一個圓圈,程序將要求半徑。如果 它是一個矩形,它會詢問長度和寬度。 收到適當的尺寸後,程序將計算所需形狀的面積和周長,並將其打印在屏幕上。再次,代碼 將要求另一封信。如果用戶輸入'Q',則程序終止。如何在一個while循環中使用開關盒

#include <stdio.h> 
#include <stdlib.h> 

int main() 
{ 
    float PI = 3.1415; 
    char choice; 
    float area, parameter; 
    int radius, side, length, width; 

    do{ 
     printf("Please enter a shape(C:Circle, S:Square, R:Rectangle, Q:Quiit> "); 
     scanf("%s", &choice); 

     switch(choice){ 
     case 'C': 
      printf("Enter a radius of the circle: "); 
      scanf("%d", &radius); 
      area = (2*radius)*PI; 
      parameter = 2*PI*radius; 
      printf("The area of the circle is %.02f and parameter is %.02f", area, parameter); 
     break; 

     case 'S': 
      printf("Enter the side of the square: "); 
      scanf("%d", &side); 
      area = side * side ; 
      parameter = 4*side; 
      printf("The area of the circle is %.02f and parameter is %.02f", area, parameter); 
     break; 

     case 'R': 
      printf("Enter the width of the rectangle: "); 
      scanf("%d", &width); 
      printf("Enter the length of the rectangle: "); 
      scanf("%d", &length); 
      area = length*width; 
      parameter = (2*length)+(2*width); 
      printf("The area of the circle is %.02f and parameter is %.02f", area, parameter); 
     break; 

     case 'Q': 
      printf("Thank and bye"); 
     break; 

     default: 
      printf("Invalid input"); 

    } 
     return 0; 
    } while (choice != 'Q'); 
} 
+0

這是'返回0;'你留在你的while循環,那將跳出無論工作,你是在 – congusbongus

+0

應該是'的scanf(「%C」,與選擇)。 ' – BLUEPIXY

回答

5

,因爲你使用的是while循環中return聲明它只運行一次:

return 0; 

main return語句擊中時會結束程序。由於裏面的while循環,它永遠不會循環。第一次被擊中它將結束程序,並且你永遠不會循環。

移動while循環下面:

} while (choice != 'Q'); 
return 0; 
1

你需要移動return 0循環之下。

0

您在while循環中有return 0。所以一旦switch語句結束,程序返回0並且不能檢查while循環條件。將return 0移出循環。

} while (choice != 'Q'); return 0;