c++ - 代码供用户从 3 个公式中选择来计算三角形的面积
问题描述
我最近完成了这段代码。它将询问用户要使用哪种类型的公式来计算三角形的面积。我想知道的是如何改进此代码并使其更高效。
3种方式是:
- 苍鹭公式(使用 sqrt)
- 角度的使用
- 正常的方式
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int formula;
cout<<"Pick a Formula for computing the area for triangles"<<endl;
cout<<"1. Heron's Formula"<<endl;
cout<<"2. 2 sides and an angle"<<endl;
cout<<"3. Given a base and a Height"<<endl;
cout<<"Formula";
cin>>formula;
switch (formula){
case 1:
int a=0, b=0, c=0, sa=0, s=0, rt=0;
cout<<"Formula is sqrt s(s-a)(s-b)(s-c) where s is (a+b+c)/2"<<endl;
cout<<"Input Parameters"<<endl;
cout<<"a";
cin>>a;
cout<<"b";
cin>>b;
cout<<"c";
cin>>c;
sa=(a+b+c)/2;
s=sa*(sa-a)*(sa-b)*(sa-c);(s);
rt=sqrt(s);
cout<<"The area of the triangle is "<<rt<< "square units";
break;
}
switch (formula){
case 2:
int angle=0, a=0, b=0, zi=0, za=0;
cout<<"Formula is 1/2ab sin (angle)"<<endl;
cout<<"Input Parameters"<<endl;
cout<<"Angle";
cin>>angle;
cout<<"a";
cin>>a;
cout<<"b";
cin>>b;
za=(a*b)/2;
zi=za*(sin(angle));
cout<<"The area of the triangle is "<<zi<<" square units";
break;
}
switch (formula){
case 3:
int ba=0, h=0, area=0;
cout<<"Formula is 1/2bh"<<endl;
cout<<"Input Parameters"<<endl;
cout<<"b";
cin>>ba;
cout<<"h";
cin>>h;
area=ba*h/2;
cout<<"The area of the triangle is "<<area<<" square units";
break;
}
}
没有问题。它工作得很好。我只想知道它是否可以以占用更少空间并提高效率的方式制造。无论如何,如果您通过此问题,请随时使用此代码。
解决方案
问题不清楚。但是您可以在这里做的是使用这样的单个 switch 语句:
switch(formula) {
case 1 : {
// code
break;
}
case 2 : {
// code
break;
}
}
注意:根据这个问题->为什么不能在switch语句中声明变量?并且因为你在里面声明了变量,你应该使用花括号来定义一个范围
推荐阅读
- python - keras:多分支非共享权重网络输入问题。收到的完整形状:(无,无,无,无)
- jquery - BoostrapTable() 列过滤器
- python - 如何在python的图中展开文本框
- javascript - javascript中的执行顺序
- c - 我的数组项在 C 编程中不断被覆盖
- javascript - 原点值不正确。请设置为最顶层页面的-(window.location.protocol + '//' + window.location.host)
- r - R:情节:树形图:仅颜色最低的标签
- apache-spark - PySpark 导入语句运行了很长时间
- typescript - “字符串”类型与 yourTableWhereUniqueInput 类型没有共同的属性
- jestjs - Angular AG Grid Jest 无法读取 null 的属性(读取“注入器”)