2013-11-04 43 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循环我的意思是 –