【发布时间】:2020-06-24 09:55:46
【问题描述】:
该程序是将日元、欧元或英镑(取决于用户输入)转换为美元。
我要求 2 个用户输入 - 双倍金额(要兑换的钱)和 char 货币(以确定要兑换成美元的货币)。
样本输入:1y
样本输出:1 日元 = 0.0094 美元。
当我尝试将欧元转换为美元时,问题出在 if-else 块中,它打破了 while 循环。这是我的代码:
double amount; // the amount of money to be converted
char currency; // to determine the currency in which the money is being entered in.
while (cin >> amount >> currency) {
if (currency == 'y' || currency == 'Y') {
cout << amount << " yen(s) = " << (amount * 0.0094) << " dollar(s).\n";
}
else if (currency == 'e' || currency == 'E') {
cout << amount << " euro(s) = " << (amount * 1.13) << " dollar(s).\n";
}
else if (currency == 'p' || currency == 'P') {
cout << amount << " pound(s) = " << (amount * 1.25) << " dollar(s).\n";
}
else {
cout << "Sorry I did not recognize the currency! Please enter 'y','e' or 'p'.\n";
}
cout << "Please enter the amount of money and corresponding currency to covert to dollars: ";
}
这里有我输入和输出的图像作为证据:
欧元兑换美元错误一
欧元兑换美元错误二
【问题讨论】:
-
请在问题中包含minimal reproducible example。
amount和currency是什么? -
可能当您输入
1e或2E时,程序会将其视为单个值(科学记数法)并退出您的while循环。 -
1Y 和 1P 可以解释为 1 个十进制数和 1 个字符,但 1E 可以解释为单个十六进制数,没有字符,打破循环的条件。
-
@Shayna "所以当它读取 "1E" 时,它会将其存储为数量,因为 1E 转换为十进制 30,它适合双精度数。" 不不。在您提出索赔之前,您是否尝试过验证您的索赔?
std::cin,可以读取科学计数法中的数字(例如 1E+1),所以当它看到1E时,它期望这种形式的数字,但由于没有指数 -std::cin失败。这就是循环停止的原因:由于输入操作失败。 -
我不是要求进一步最小化代码,而是要添加缺少的细节。您只在文本中提及类型是什么,但在代码中缺少声明。如果您的代码可以被其他人复制以重现您面临的相同问题,那总是更容易
标签: c++ visual-c++