C++计算圆锥体积的程序

C++program that calculates the volume of a cone

本文关键字:程序 圆锥体 计算 C++      更新时间:2023-10-16

我在编译这段代码时没有问题,但它无法正常运行。这是我的源代码:

#include <iostream>
#include <cmath>
using namespace std; 
int main(){
    float height;
    float radius;
    float volume;
    volume=.3333333333333333333333333333333*radius*radius*height;

    cout<<"Enter height:"<<endl;
    cin>>height;
    cout<<"Enter radius:"<<endl;
    cin>>radius;
    if(height==0&&radius==0){
        cout<<"Not a valid solution";
    }
    if(height==0&&radius!=0){
        cout<<"not a valid a solution"<<endl;

    }
    if(height!=0&&radius==0){
        cout<<"not a valid solution"<<endl;
    }
    if(height<0&&radius<0){
        cout<<"Not a valid solution";
    }
    if(height<0&&radius>0){
        cout<<"Not a valid solution";
    }
    if(height>0&&radius<0){
        cout<<"Not a valid solution";
    }
    if(height>0&&radius>0){
        cout<<"Volume is "<<volume<<endl;
    }
    return 0;
}

但是当我运行它并要求我输入半径和高度的值时,体积始终为零:这是我的意思:

Enter height:
9.0
Enter radius:
9.0
Volume is 0

我做错了什么?

C++是一种顺序编程语言,而不是声明式编程语言。语句通常从上到下执行(函数调用、goto 和循环等跳转指令除外)。因此,当您执行此操作时:

volume=.3333333333333333333333333333333*radius*radius*height;

计算使用 radiusheight 的当前值(在执行此语句时,这两个值均未初始化)。volume的值不会在以后radiusheight更改时更新。将该语句放在用户输入的值之后

如果您希望 volume 的值使用 heightradius 自动更新,您可以将其设为 lambda:

auto volume = [&radius,&height]() {
    return .3333333333333333333333333333333*radius*radius*height;
};
cin >> radius >> height;
cout << volume() << 'n';

顺便说一句,你有很多多余的支票。您的所有if语句都可以简化为:

if (height <= 0 || radius <= 0) {
    // not a valid solution
}
else {
    // calculate and print solution
}

很确定您在提供任何高度和半径之前就设置了音量,请尝试将其移动到 cin 以下,如果仍然不起作用,请返回

您在接受用户输入之前正在计算volume。移动线条

volume=.3333333333333333333333333333333*radius*radius*height;

到之后

cin>>radius;

此行已在编译时计算:

volume=.3333333333333333333333333333333*radius*radius*height;

最好的办法是创建一个函数,并在用户输入完半径和高度后调用它:

float calculate_volume(float r, float h)
{
    return .3333333333333333333333333333333*r*r*h;
}
if(height>0&&radius>0){
    cout<<"Volume is "<< calculate_volume(radius, height) <<endl;
}