簡體   English   中英

簡單函數C ++

[英]Simple Function C++

using namespace std;
int main()
{

return 0;
}
double C2F()
{
    f = value * 9 / 5 + 32;
    return f;
}

double K2F()
{
    f = (value - 273.15) * 1.8 + 32.0;
    return f;
}

double N2F()
{
    f = value * 60 / 11 + 32;
    return f;
}

我在調用這些函數來計算溫度轉換而不是從案例中計算溫度轉換時遇到麻煩。 添加這些功能后,該程序甚至無法編譯。 “錯誤:預期為“;””

您不能在另一個函數中聲明或定義函數。 將您的定義移到int main(){ ... }

首先,您不能在main()函數中聲明另一個函數。

其次,所有函數都具有返回類型,但是令人驚訝的是您正在調用它們,因為它們是無效的。 使該函數無效,而不是返回類型。 例如...

void C2F()
{
    f = value * 9 / 5 + 32;
}

接着

case 'C':
        C2F();
        cout << value << "C is " << f << " in Farenheit" << endl;
        break;

要么。 您可以在雙精度類型變量中接收返回值並打印該值。

case 'C':
    cout << value << "C is " << C2F() << " in Farenheit" << endl;
    break;

這就是你想要的。

  1. 在main方法之外聲明函數。
  2. 在main方法之前聲明函數或使用前向聲明
  3. 將“值”作為參數傳遞給每個函數。
  4. 刪除不必要的變量聲明。
  5. 對用戶輸入使用一些驗證。
  6. 使用有意義的變量名。

包括

using namespace std;


double C2F(double f)
{       
    return f * 9 / 5 + 32;    
}

double K2F(double f)
{   
    return ((f - 273.15) * 1.8 + 32.0);   
}

double N2F(double f)
{           
    return (f * 60 / 11 + 32);

}

int main()
{
    char function;
    double value;
    cout << "This temperature Conversion program converts other temperatures to farenheit" << endl;
    cout << "The temperature types are" << endl;
    cout << "" << endl;
    cout << "C - Celcius" << endl;
    cout << "K - Kelvin" << endl;
    cout << "N - Newton" << endl;
    cout << "X - eXit" << endl;
    cout << "" << endl;
    cout << "To use the converter you must input a value and one of the temperature types." <<         endl;
    cout << "For example 32 C converts 32 degrees from Celsius to Fahrenheit" << endl;
    cin >> value >> function;

    function = toupper(function);

    while (function != 'X')
    {
        switch (function)
        {
        case 'C':       
            cout << value << "C is " << C2F(value) << " in Farenheit" << endl;
            break;
        case 'K':       
            cout << value << "K is " << K2F(value) << " in Farenheit" << endl;
            break;
        case 'N':
            cout << value << "N is " << N2F(value) << " in Farenheit" << endl;
            break;
        default:
            cout << "Correct choices are C, K, N, X" << endl;
        }
        cout << "Please enter a value and it's type to be converted" << endl;
        cin >> value >> function;
        function = toupper(function);
    }
    return 0;
}

暫無
暫無

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

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