gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 05:52:30 28 4
gpt4 key购买 nike

我一直在尝试创建一个工作程序,将其他形式的全局货币(例如日元、克朗和英镑)转换为美元。我试过引用谷歌上的经济汇率设置货币值(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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com