2013-10-13 29 views
0

以下提示輸入半徑和高度,並使用這些值計算圓柱體的體積。我怎樣才能編寫這個程序,以便在用戶輸入任何一個高度半徑的負值時不會終止?範圍必須爲1-10,並且不允許其他提示。只有在輸入非數字時才能終止循環。如何在C中完成這項任務?第2部分

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


float areaCirc(float r){ 
return (M_PI*r*r); 
} 

float volCyl(float r, float h){ 
return (areaCirc(r)*h); 
} 


int main(void) { 
float r, h; 
int k = 0; 
float volume; 
float avgh = 0; 
float toth = 0; 

do{ 
    float exit = scanf("%f%f", &r, &h); 
    if (exit == 0) 
    {break;} 
    if(r<=0 || r>10){ 
     printf("Invalid radius: %.2f\n",r); 
    } 
    if(h<=0 || h>10){ 
     printf("Invalid height: %.2f\n",h); 
    } 
    if(r>=0 && r<=10 && h>=0 && h <= 10){ 
    volume = volCyl(r,h); 
    k = k++; 
    printf(" Cylinder %d radius %.2f height %.2f volume %.2f\n",k,r,h,volume); 
    toth = toth + h; 
} }while(r>0 && h>0); 
    avgh = toth/k; 
    printf("Total Height: %.2f\n",toth); 
    printf("Average Height: %.2f\n",avgh); 

return EXIT_SUCCESS; 
} 

回答

0

我的指定範圍必須是1以上10以下,不終止該程序的負值,並且沒有其它的提示被允許

修改ÿ我們的主要功能

do{ 
    int ex = scanf("%f%f", &r, &h); //scanf returns int 

    if (ex == 0) 
    {break;} 
    if(r<=0 || r>10){ 
     printf("Invalid radius: %.2f\n",r); 
     continue; 
    } 
    if(h<=0 || h>10){ 
     printf("Invalid height: %.2f\n",h); 
     continue; 
    } 
    // hence above conditions failed means you have given desired input 
    // need not to check any conditions 
    volume = volCyl(r,h); 
    k = k++; 
    printf(" Cylinder %d radius %.2f height %.2f volume %.2f\n",k,r,h,volume); 
    toth = toth + h; 
    }while(r>0 && h>0); 

    if(k>0) // check this other wise divide by zero will occur 
    { 
    avgh = toth/k; 
    printf("Total Height: %.2f\n",toth); 
    printf("Average Height: %.2f\n",avgh); 
    } 
+0

我指定的範圍必須是1至10包容性,沒有負值終止程序,並且不允許其他提示 – user2805620

+0

當用戶輸入11或-1作爲輸入時是否要打印錯誤。我的意思是1-10的範圍 – Gangadhar

+0

我想打印無效半徑或無效高度(如果它們超出範圍),並繼續提示輸入而沒有文本引導它們,並且循環僅在輸入非數字時纔會終止。 – user2805620

1

看看你的while()中的語句。請注意,當且僅當這些條件結果爲真時,這將保持循環。

+0

我知道,但我不知道如何使它包括所有正在範圍的值,即負值幷包括0 – user2805620

1
do { 
    printf("Enter radius: ") 
    scanf("%d", &r); 
    printf("Enter height: ") 
    scanf("%d", &h); 
} while(r<=0 || h<=0); 

您可以使用一個do-while循環將繼續提示用戶重新輸入半徑和高度要麼值小於或等於0。

希望這有助於:)

相關問題