C++计算圆锥体积的程序
C++program that calculates the volume of a cone
我在编译这段代码时没有问题,但它无法正常运行。这是我的源代码:
#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;
计算使用 radius
和 height
的当前值(在执行此语句时,这两个值均未初始化)。volume
的值不会在以后radius
和height
更改时更新。将该语句放在用户输入的值之后。
如果您希望 volume
的值使用 height
和 radius
自动更新,您可以将其设为 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;
}
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- C++,系统无法执行指定的程序
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到
- 重载操作程序时出错>>用于类中的字符串 memebr
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 试图在visual studio上用C++创建一个桌面应用程序
- 模板元程序查找相似的连续类型名称
- FFmpeg:制作一个应用程序比直接使用ffmepg更好吗
- 如何通过cpp程序运行shell脚本
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- IPC使用多个管道和分支进程来运行Python程序
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 使用C++程序合并排序没有得到正确的输出
- 基于boost的程序的静态链接——zlib问题
- 程序崩溃并显示"std::out_of_range"错误
- 在C应用程序中运行C++(带有STL)函数
- 使用mongocxx驱动程序时包含头文件问题
- 用C++程序计算圆锥体的体积、球体的体积、八边形的面积和两点之间的距离