如何在C++美元兑换外币程序的全局区定义汇率常量
C++美元兑换程序全局汇率常量实现方案
具体修改逻辑
- 全局常量需要定义在所有函数外部,使用
const修饰保证值不可篡改,全程序所有位置都可直接读取 - 修复原代码的两处问题:
- 原代码将函数定义嵌套在main函数内部,C++不支持函数嵌套定义,需要移到main外
- 原代码将汇率和兑换结果共用同一个变量,第一次调用兑换函数后汇率会被覆盖,导致第二次计算结果错误,拆分汇率常量和结果变量修复该问题
修改后完整代码
#include <iostream> #include <iomanip> #include <cmath> using namespace std; // 全局汇率常量定义,全局作用域可访问,值不可修改 const float EURO_RATE = 1.06; const float PESO_RATE = 9.73; const float YEN_RATE = 124.35; void convertMulti(float d, float&, float&); void convertMulti(float d, float&, float&, float&); int main () { float dollars; cout << fixed << showpoint << setprecision(2); cout << "请输入你想要兑换为欧元和比索的美元金额:" << endl; cin >> dollars; float euros, pesos; convertMulti(dollars, euros, pesos); cout << "$" << dollars << " 可兑换为 " << euros << " 欧元、" << pesos << " 比索" << endl; cout << "请输入你想要兑换为欧元、比索和日元的美元金额:" << endl; cin >> dollars; float yen; convertMulti(dollars, euros, pesos, yen); cout << "$" << dollars << " 可兑换为 " << euros << " 欧元、" << pesos << " 比索、" << yen << " 日元" << endl; return 0; } // 兑换为欧元、比索的重载函数 void convertMulti(float d, float& e, float& p) { e = d * EURO_RATE; p = d * PESO_RATE; } // 兑换为欧元、比索、日元的重载函数 void convertMulti(float d, float& e, float& p, float& y) { e = d * EURO_RATE; p = d * PESO_RATE; y = d * YEN_RATE; }
内容的提问来源于stack exchange,提问作者Harry202020
相关产品推荐
相关产品推荐

