在C中将值从一个函数传递给另一个函数

时间:2018-12-07 07:36:57

标签: c function variables

我试图将一个函数确定的值传递给它之后的另一个函数。本质上:函数1确定一个值,比方说x。然后,将X传递到另一个专门将X显示为文本的函数。它在一个单独的函数中,供其他也可以确定X值的函数使用。但是,我只得到0而不是变量x。怎么了?

float fahToCel(int userInput)
{
    float result = 0;
    do
    {
        printf("\nPlease input your number in Fahrenheit units:");
        scanf("%d", &userInput);
    } while (result = 0);
    result = (float)(((float)5.0f / (float)9.0f) * (float)(userInput - 32));
    return result;
}

float celToFah(int userInput){
    float result = 0;
    do
    {
        printf("\nPlease input your number in Celcius units:");
        scanf("%d", &userInput);
    } while (result = 0);
    result = (float)(((float)9.0f / (float)5.0f) * (float)(userInput + 32));
    return result;
}

float displayResult(float result) {
    printf("\nThe equivalent tempature is: %f\n", result);
    return result;
}

void inputInformation() {
    printf("1. Convert temperature input from the user in degrees Fahrenheit to 
    degrees Celsius.\n");
    printf("2. Convert temperature input from the user in degrees Celsius to 
    degrees Fahrenheit.\n");
    printf("3. Quit.\n ");
}


int main()
{
    int menuChoice = 0;
    int userInput = 0;
    int result = 0;
    while (1)
    {
        inputInformation();
        printf("Please make a selection now:");
        scanf("%d", &menuChoice);

        switch (menuChoice)
        {
            case 1:
                 fahToCel(userInput);
                 displayResult(result);
                 break;
            case 2:
                 celToFah(userInput);
                 displayResult(result);
                 break;
            case 3:
                 return 0;
            default:
                 printf("\nThat is not a choice!\n");
                 break;
        }
    }
}

1 个答案:

答案 0 :(得分:3)

您永远不会将结果分配给result。更改如下:

result = fahToCel(userInput);
displayResult(result);