C++——如何使用 switch 语句和 constexprs 获得一个可用的货币转换器?

标签 c++ visual-studio switch-statement currency constexpr

我一直在尝试创建一个工作程序,将其他形式的全局货币(例如日元、克朗和英镑)转换为美元。我试过引用谷歌上的经济汇率设置货币值(value)(转换为美元)。 该程序使用 constexprs 来初始化对应于不同货币的数值,以及使用 switch 语句来表示不同货币以进行转换的字符。但是,我无法让它按预期工作。

在运行时,编译项目构建后,任何值都会自动引用 switch 语句的“default:”段。 感谢任何有关如何使它正常工作的帮助。

我的包含来自标准 C++ 库头文件,其中主要头文件包括: #include iostream #include fstream #include sstream #include cmath #include cstdlib #include string #include list #include vector #include algorithm #include stdexcept

这是我的代码:

    int main()

    {

    constexpr double yuan_to_dollar = 0.15; // conversion to USD -- values cannot be modified at runtime

constexpr double kroner_to_dollar = 0.15;

constexpr double pound_to_dollar = 1.42;

char currency;
char yuan = 'a';
char kroner = 'b';
char pound = 'c';

double amount = 1;

cout << "Please enter an integer amount in currency: \n";

cin >> currency >> amount >> yuan >> kroner >> pound; // inputs currency double values

switch (currency) {

case 'a':
    cout << yuan << "is == " << yuan_to_dollar * 'a' * amount << "currency \n";

case 'b':
    cout << kroner << "is == " << kroner_to_dollar * 'b' * amount << "currency \n";

case 'c':
    cout << pound << "is == " << pound_to_dollar * 'c' * amount << "currency \n";

default:
    cout << "Sorry, I could not determine a suitable form of: " << currency << "currency \n";
}

return 0;

最佳答案

switch/case 的正确形式是:

switch(currency) {
    case 'a':
        // code in case of a here
        break;
    case 'b':
        // code for b here
        break;
    default:
        // default case
}

否则你将无法通过所有陈述。

另外不要乘以 'a','a' 的整数值为 97,因此对于 a,您要乘以 0.15 * 97。

您的输入似乎也不是您要查找的内容。

你写的方式: cin >> currency >> amount >> yuan >> kroner >> pound;

将接受字符(货币)、金额(双倍)和另外三个字符(元、克朗、英镑)的输入。这样做会覆盖字符。

关于C++——如何使用 switch 语句和 constexprs 获得一个可用的货币转换器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34936835/

相关文章:

c++ - 对同一类的多个不同对象使用 1 个唯一的 MFC 对话框

ios - Switch 语句嵌套格式 - 哪个是正确的?

java - 使用 Maven 编译并执行 JDK 预览功能

c++ - 有条件地将映射键复制到 vector

c++ - C++11 中单独的枚举声明和定义

c++ - 'if constexpr'理解错误

c++ - 如何从 C++ 中的字符串中提取多组动态数字?

c++ - fatal error LNK1104 : cannot open file "Debug/

c++ - 在字符串的 std::map 中查找编译错误,长

java - 带 Switch 语句的 While 循环