2014-03-07 92 views
0

我只是想讓程序取1到9之間的數字並計算半徑並顯示它。這個程序應該循環,但我得到的是「感謝您使用該軟件!」打印功能,它沒有經過循環,我似乎無法理解爲什麼。循環跳過語句

#include <stdio.h> 
int main(void){ 

float i,r, V; 
for(i=0; i <= 4; i++){ 
    while (r != 0) { 
     printf("Enter a radius between 1 and 9: \n"); 
     scanf ("%f", &r); 
     V= (3.141592)*r*r*10; 
     if (r>=1 && r<=9){ 
      printf("The cylinder volume is %f\n", V); 
     } 
     else if (r > 9 || r < 0){ 
      printf ("The input is out of the acceptable range. Select an integer less than $/n"); 
     } 
     printf("Thank you for using the software!\n"); 
    } 
    return 0; 
} 

回答

6

你永遠不初始化r輸入您while循環之前,所以這是不確定的行爲。

此外,你想要使用int s爲平等運營商,即==!=。在你的情況下,你可能想包含一個r可以在其中的「錯誤」。

+0

你是什麼意思我不初始化r,我仍然是一個noob,所以我的行話有點慢。 – Levetica

+0

這意味着你永遠不會給它賦值,所以它會給你垃圾(無論以前在那個內存位置)。初始化意味着你爲它分配一個合法的值,即'r = 1.0;' –

+0

好吧,我明白什麼是初始化意味着現在,但如果我不知道用戶將輸入什麼值,我將如何爲變量賦值。程序的要點是要求用戶輸入1到9之間的數字,並將該數字分配給變量r,進行計算,再次將答案重新分配給r,然後顯示該數字。在我知道哪些數字可以分配之前,我如何將r分配給一個數字? – Levetica

1

在使用它之前,您還沒有初始化r。 你必須初始化它或使用i遍歷循環。

INITIALIZE r here before using 
    for (i = 0; i <= 4; i++) 
    { 
     while (r != 0) 
     { 
      //code 
     } 
    } 
+0

他應該在'for'循環中初始化'r',否則它將永遠不會再次進入(不是我知道'for'是什麼意思。) – ugoren

+0

ofcourse他可以初始化循環中的r但是它會被執行多次,所以它不是一個好主意,我猜想。 –

+0

沒有真正知道他想做什麼,這是一個徒勞無益的論點。 – ugoren

0

你最好使用do while loop來做你想做的事情。

for(i=0; i <= 4; i++){ 
    do { 
     printf("Enter a radius between 1 and 9: \n"); 
     scanf ("%f", &r); 
     V= (3.141592)*r*r*10; 
     if (r>=1 && r<=9){ 
      printf("The cylinder volume is %f\n", V); 
     } 
     else if (r > 9 || r < 0){ 
      printf ("The input is out of the acceptable range. Select an integer less than $/n"); 
     }while (r != 0) 
     printf("Thank you for using the software!\n"); 
    } 

我還沒有嘗試過這個由我self.this可能work.try它,如果它的工作。