我的第二个函数stub似乎无限循环?

时间:2013-11-04 01:23:22

标签: c function loops stub infinite

我有两个相对相同的存根函数,但当我调用第二个存根时,它似乎是无限循环,我不知道为什么。我在这段代码中调用的函数是无限循环是convert_weight();.我怀疑它是否是一个主程序问题,因为它被调用并打印出前几个printfs而没有问题但是当使用来自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;
}

1 个答案:

答案 0 :(得分:2)

您在scanf函数中使用了错误的convert_weight格式说明符:

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

它应该是%d,它读取一个整数。