该程序将日元,欧元或英镑(取决于用户输入)转换为美元。
我要问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: ";
}
作为证据,这里是我输入和输出的图像:欧元转换为美元错误一
欧元转换为美元错误二
最佳答案
提供实际答案,因为我无法在评论中提供;这是获取相关用户输入并保持相同语法的另一种方法。假定输入字符串的最后一个字符是货币字符。您可以检查最后一个字符是否是有效的货币字符,但这是简化的版本。
#include <iostream>
#include <string>
int main() {
std::string input_string;
std::getline(std::cin, input_string);
if(input_string.size() >= 2) {
char currency = input_string[input_string.size() - 1];
input_string[input_string.size() - 1] = '\0';
double amount = std::stof(input_string);
std::cout << amount << std::endl;
std::cout << currency << std::endl;
}
}
关于c++ - 在if语句C++中意外中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62552352/