我有兩個相對相同的存根函數,但是當我打電話給第二個存根似乎無限循環,我不知道爲什麼。我在這段無限循環的代碼中調用的函數是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;
}
想一想當convert_weight中'a!= 2'發生了什麼 - b不能保證爲0 –
當然'length_to_us'應該是'length_to_imperial'。也不需要那些回報。 –