首页 > 解决方案 > 代码供用户从 3 个公式中选择来计算三角形的面积

问题描述

我最近完成了这段代码。它将询问用户要使用哪种类型的公式来计算三角形的面积。我想知道的是如何改进此代码并使其更高效。

3种方式是:

  1. 苍鹭公式(使用 sqrt)
  2. 角度的使用
  3. 正常的方式
#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;
    }
}

没有问题。它工作得很好。我只想知道它是否可以以占用更少空间并提高效率的方式制造。无论如何,如果您通过此问题,请随时使用此代码。

标签: c++math

解决方案


问题不清楚。但是您可以在这里做的是使用这样的单个 switch 语句:

switch(formula) {
case 1 : {
         // code
         break;
         }
case 2 : {
         // code
         break;
         }
}

注意:根据这个问题->为什么不能在switch语句中声明变量?并且因为你在里面声明了变量,你应该使用花括号来定义一个范围


推荐阅读