c++ 为什么我不能从变量的定义中调用函数?

hk8txs48  于 2023-02-06  发布在  其他
关注(0)|答案(3)|浏览(145)

我已经包含了我在下面写的代码。我已经创建了一个函数,它根据用户的输入计算圆锥体的体积。这是按预期工作的。

# include <iostream>
# include <string.h>
# include <string>

using namespace std;

// ConeVolume prototype
float ConeVolume(float radius, float height);

int main()
{
    // Establish variables 
    float radius1;
    float height2;
    float volumeCone = ConeVolume(radius1, height2);

    // User input to define the varibales
    cout << "Radius: ";
    cin >> radius1;
    cout << "Height: ";
    cin >> height2;

    // Return variable using the ConeVolume function
    cout << endl << "Cone Volume: " << volumeCone;

    return 0;
}

// Function that calculates the volume of a Cone
float ConeVolume(float radius, float height)
{
    float pi = 3.14;
    float volume = (pi/3)*(radius * radius) * (height);
    
    return volume;
}

我的问题是...如果我通过输出变量“float ConeVolume”来调用函数,如下所示,为什么程序返回“0”?我不能将变量的值设置为等于函数吗?

// Return variable using the volumeCone float variable
    cout << endl << "Cone Volume: " << volumeCone;
4uqofj5v

4uqofj5v1#

你只是犯了一个愚蠢的错误。你在接受用户输入之前调用了'ConeVolume'函数。所以,只有垃圾值被传递给了函数。

# include <iostream>
# include <string.h>
# include <string>

using namespace std;

// ConeVolume prototype
float ConeVolume(float radius, float height);

int main()
{
    // Establish variables 
    float radius1;
    float height2;

    //wrong code here
    // you've called the function before taking input of radius1 and height2
    //float volumeCone = ConeVolume(radius1, height2);

    // User input to define the varibales
    cout << "Radius: ";
    cin >> radius1;
    cout << "Height: ";
    cin >> height2;

    // Correct code:
    // Call the function after taking input
    float volumeCone = ConeVolume(radius1, height2);

    // Return variable using the ConeVolume function
    cout << endl << "Cone Volume: " << volumeCone;

    return 0;
}

// Function that calculates the volume of a Cone
float ConeVolume(float radius, float height)
{
    float pi = 3.14;
    float volume = (pi/3)*(radius * radius) * (height);
    
    return volume;
}

希望这个有用。

dpiehjr4

dpiehjr42#

程序返回0,因为在更改radius1height2的值后,volumeCone的值没有更新。
必须再次调用函数coneVolume(),或者最好在定义了radius1height2之后调用它。

int main()
{
    // Establish variables 
    float radius1;
    float height2;

    // User input to define the varibales
    cout << "Radius: ";
    cin >> radius1;
    cout << "Height: ";
    cin >> height2;

    float volumeCone = ConeVolume(radius1, height2);

    // Return variable using the ConeVolume function
    cout << endl << "Cone Volume: " << volumeCone;

    return 0;
}
qfe3c7zg

qfe3c7zg3#

插入行
体积圆锥体=圆锥体体积(半径1,高度2);
线后
cin〉〉高度2;
然后换线
浮子体积锥=锥体积(半径1,高度2);

浮子容积锥;

相关问题