C++ - 如何添加函数以处理货币计算器的多种情况

C++ - How do I add functions to work on a multitude of cases for a currency calculator?

本文关键字:计算器 货币 处理 情况 函数 何添加 添加 C++      更新时间:2023-10-16
For my currency calculator, I need to add 3 different types of functions-
1) enterCostUSD (I enter the cost in USD)
2) convertCost (convert the cost from USD to, say, rupees)
3) displayOutput (display the output of the new cost)

我总共有10个案例。如何添加函数以使其适用于所有 10例?

我是否需要在每个案例的中间添加它们?

这是其中一种情况,我需要以这种方式进行还是有更好的方法?

    case 1: //Finding cost in Altairian Dollars
    cout << "Enter the cost in US Dollars: ";
    cin >> enterCostUSD;
    altairianDollars = enterCostUSD*0.72
    cout << "$" << enterCostUSD << " is equal to " << altairianDollars   
    cout << "Thank You for using the Currency Calculator!" << endl;
    break;

我从你的问题中了解到的是,你有 10 种情况试图转换货币。因此,为此,您必须创建10个案例,就像您在问题中提到的一样。

如果所有情况通用的任何功能,您可以将其保留在一个函数中并从每个cases.调用它

在这里,打印输出和转换货币是可以分开的功能。

例如:

 case 2: //Finding cost in Rupee
    CostUSD=enterUSDCost();//function 1
    conversion_rate=63.5;//for rupee
    Rupee = convertCost(CostUSD,conversion_rate);//function2
    displayOutput(enterCosstUSD,Rupee,"Rs");//function 3
    break;

这三个函数需要超出你的主函数的范围,这是三个独立的函数。

float enterCostUSD()
{
float USD_cost;
cout << "Enter the cost in US Dollars: ";
        cin >> USD_cost;
return USD_cost;
}
float convertCost(float USD, float rate)
{
return USD*rate;
}
void displayOutput(float enterCostUSD, float Rupee,string conversion_currency){
cout << "$" << enterCostUSD << " is equal to " << Rupee <<conversion_currency   ;
    cout << "Thank You for using the Currency Calculator!" << endl;
    }

如果您想更好地了解开关情况,请点击此链接