簡體   English   中英

您如何從調用的函數向主函數返回值?

[英]How do you return a value from a called function to the main?

我使用return命令,然后嘗試從主菜單打印值。 它返回零(0)的值。

這個程序是關於從攝氏溫度到華氏溫度的轉換。

另外,如何使用舍入函數將答案舍入為整數,因此它不是帶小數的浮點數。

#include <stdio.h>

int Cel_To_Fah(int a, int b); // function declaration

int main (void)

{

    int a;
    int b;

    printf(" Enter temperatrure:  "); scanf("%d", &a);

    Cel_To_Fah(a,b); // function call

    printf("The temperature is: %d\n", b);

    return 0;

} // main

int Cel_To_Fah(a,b)

{

    b=1.8*a+32;

    return b;

} // Cel_To_Fah

您只需要使用賦值運算符:

b = Cel_To_Fah(a);

但是,您的程序有很多問題,包括Cel_To_Fah函數沒有正確的簽名。 您可能想要類似的東西:

int Cel_To_Fah(int a)
{
    return 1.8 * a + 32;
}

您可能應該會獲得一本不錯的初學者C書。

不需要函數(b)的第二個參數。

您可以通過...

      #include<stdio.h>
    int Cel_To_Fah(int a); // function declaration, as it returns a values;


     int main (void)
       {
       int a; int b;

       printf(" Enter temperatrure: "); 
       scanf("%d", &a);
       b = Cel_To_Fah(a); /* the returned value is stored into b, and as b is an integer so it is automatically rounded. no fraction point value can be stored into an integer*/
       printf("The temperature is: %d\n", b);
       return 0;
       } // main

     int Cel_To_Fah(int a)
       {
       return 1.8 * a + 32;
       }

有幾個問題。 首先,您需要使用float而不是int,以便您可以使用帶小數點的值。 否則,您的計算將出錯。 出於相同的原因,也請使用32.0而不是32。

其次,您需要了解函數中的a和b與main中的a和b不同。 它們具有相同的名稱,但不在同一“作用域”中。 因此,更改函數中的一項不會影響main中的一項。 這就是為什么在main中必須說b = Cel ...以便main中的b將獲得返回值的原因。

最后,在c中,應該將函數放在main之上/之前。 否則,盡管有些現代的編譯器會為您解決該問題,但從技術上講它還沒有定義為“還”。 閱讀有關函數原型的信息。

由於您的函數Cel_To_Fah(a,b); 返回一個值( int類型),則必須將其分配給其返回類型( int類型)的變量。

 int a;
 int b;

printf(" Enter temperatrure:  "); scanf("%d", &a);

b = Cel_To_Fah(a); // function call

printf("The temperature is: %d\n", b);  

而你的功能應該是

int Cel_To_Fah(a)
{
    int b = 1.8*a+32;
    return b;
 } // Cel_To_Fah  

並且不要忘記將功能原型更改為

int Cel_To_Fah(int a);

我在您的代碼中看到了兩個問題。 首先,它是變量類型。 我假設您希望攝氏溫度為整數; 但華氏= 1.8 *攝氏+32應該是浮點數。 因此,b應該是浮點的。

其次,您不應該通過函數的輸入參數返回值(除非您學習指針或通過ref調用)。 我將您的代碼重寫如下:

include<stdio.h>

float Cel_To_Fah(int a); // function declaration

int main (void)

{

    int a;
    float b;

    printf(" Enter temperatrure:  "); scanf("%d", &a);

    b=Cel_To_Fah(a); // function call

    printf("The temperature is: %.2f\n", b);  //showing 2 decimal places

    return 0;

} // main

float Cel_To_Fah(int a)

{
    float b;

    b=1.8*(float)a+32;   //cast a from int to float

    return b;

} // Cel_To_Fah

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM