2013-11-04 45 views
0

我有兩個相對相同的存根函數,但是當我打電話給第二個存根似乎無限循環,我不知道爲什麼。我在這段無限循環的代碼中調用的函數是convert_weight();.我懷疑它是否是主程序問題,因爲它被調用並打印出前幾個printf而沒有問題,但是當使用來自scanf的用戶輸入時,它會進入無限循環。任何幫助將是有用的,請和謝謝。我的第二個函數存根似乎無限循環?

#include <stdio.h> 
void convert_lengths(int users_choice); 
void convert_weight(int users_choice); 
void length_to_metric(void); 
void length_to_us(void); 
void weight_to_metric(void); 
void weight_to_us(void); 

int main() 
{ 
    int users_choice; 
    do 
    { 
     printf("Do you want to convert length or weights?\n"); 
     printf("1 for length\n"); 
     printf("2 for weights\n"); 
     printf("0 to end program\n"); 
     scanf("%d", &users_choice); 
     if(users_choice == 1) 
     { 
      convert_lengths(users_choice); 
     } 
     if(users_choice == 2) 
     { 
      convert_weight(users_choice); 
     } 
    }while(users_choice != 0); 
    return 0; 
} 
void convert_lengths(int a) 
{ 
    int b; 
    do 
    { 
     if(a == 1) 
     { 
      printf("You have chosen to convert lengths\n"); 
      printf("What units do you want to convert?\n"); 
      printf("- 1 to convert feet/inches to meters/centimeters\n"); 
      printf("- 2 to convert from meters/centimeters to feet/inches\n"); 
      printf("- 0 to go back to other options\n"); 
      scanf("%d", &b); 
      if(b == 1) 
      { 
       printf("You have chosen to convert feet/inches to meters/centinmeters\n\n"); 
       length_to_metric(); 
      } 
      if(b == 2) 
      { 
       printf("You have chosen to convert meters/centimeters to feet/inches\n\n"); 
       length_to_us(); 
      } 
     } 
    }while(b != 0); 
} 
void convert_weight(int a) 
{ 
    int b; 
    do 
    { 

     if(a == 2) 
     { 
      printf("You have chosen to convert weights\n"); 
      printf("What units of weight do you want to convert?\n"); 
      printf("- 1 for pounds/ounces to kilograms/grams\n"); 
      printf("- 2 for kilograms/gram to pounds/ounces\n"); 
      printf("- 0 to go back to other options\n"); 
      scanf("%b", &b); 
      if(b == 1) 
      { 
       printf("You have chosen to convert pounds/ounces to kilograms/gram\n\n"); 
       weight_to_metric(); 

      } 
      if(b == 2) 
      { 
       printf("You have chosen to convert kilograms/gram to pounds/ounces\n\n"); 
       weight_to_us(); 
      } 
     } 

    }while(b != 0); 
} 
void length_to_metric(void) 
{ 
    return; 
} 
void length_to_us(void) 
{ 
    return; 
} 
void weight_to_metric(void) 
{ 
    return; 
} 
void weight_to_us(void) 
{ 
    return; 
} 
+0

想一想當convert_weight中'a!= 2'發生了什麼 - b不能保證爲0 –

+0

當然'length_to_us'應該是'length_to_imperial'。也不需要那些回報。 –

回答

2

您在convert_weight函數中使用了錯誤的格式說明爲scanf

scanf("%b", &b); 
     ^

它應該是%d,其內容爲一個整數。

+0

啊,是的,謝謝!當我看到我的功能時,我似乎會看到隧道視野,但一般情況下,它總是會出現scanf問題。 –

+1

你應該把那些'if(a == 2)'測試出來。如果您要調用這些函數並提供錯誤的參數,您將會遇到無限循環。這種情況下的參數看起來完全沒有意義。 – paddy

+0

但是,這些工作是否會讓循環重複,直到我已經輸入正確的參數?通過do-while循環我的意思是 –